javascript
Javascript to find which DOM element has the focus
January 28, 2023
In JavaScript, you can use the document.activeElement property to determine which DOM element currently has the focus. This property returns the element that currently has focus, or null if no element has focus.
Javascript to find which DOM element has the focus
To find the DOM element that has the focus:
- Find the focused DOM element using document.activeElement eg: const activeElement = document.activeElement;
- Log the element in the console using console.log(activeElement). This will print the focused DOM element in the console.
Code Example:
var focusedElement = document.activeElement;
console.log(focusedElement);
You can also use document.hasFocus() to check if the document has focus or not.
console.log(document.hasFocus());
You may also use document.body.contains(document.activeElement) to check if the active element is in the body or not.
console.log(document.body.contains(document.activeElement));
Print element in the console window when focused
You can also attach an event listener to the document object and listen for the focus and blur events to detect when an element receives and loses focus.
document.addEventListener("focus", function(event) {
console.log(event.target);
}, true);
Was this helpful?
Similar Posts
- Pass multiple arguments when calling a function which takes single argument Javascript
- Array.find() - get the very first element satisfy a condition Javascript
- Get all values from an array which does not exist in other array Lodash
- Find the nth largest element in a sorted array
- Find the minimum value from an array javascript
- Find the maximum value from an array using Javascript
- Find the index of Max value in an array using Javascript