javascript

Javascript to find which DOM element has the focus

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:

  1. Find the focused DOM element using document.activeElement eg: const activeElement = document.activeElement;
  2. 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?