Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How to find which DOM element has the focus using jQuery?

  • Last Updated : 22 May, 2020

The HTML DOM has an activeElement Property. It can be used to get the currently focused element in the document:

Syntax: var ele = document.activeElement;

Return value: It returns the currently focused element in the document.
Example Code Snippets:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Example 1: var eleName = document.activeElement.tagName;
Returns: The Tag Name of the active element.

Example 2: var eleId = document.activeElement.id;
Returns: The id of the active element, if any.

Sample Code to demonstrate working:




<!DOCTYPE html>
<html>
  <head>
    <script src=
    </script>
  </head>
  <body>
  
    <p> Click wherever you like. 
The active/focused DOM name will be displayed at the end</p>
    <input type="text" value="Some input field">
    <button>Simple Button</button>
  
    <p id="fun"></p>
  
    <script>
      $("body").click(function() {
        var x = document.activeElement.tagName;
        document.getElementById("fun").innerHTML = x;
});
    </script>
  
  </body>
</html>

Explanation of the above code:
The script inside body tag modifies the HTML Content of the DOM Element having id fun to the name of the DOM Element which is currently active or is in focus. This is the value which is returned by the

document.activeElement.tagName

Output:

  1. Before clicked/focused:
  2. After clicked/focused:
  3. When input field is clicked/focused
My Personal Notes arrow_drop_up
Recommended Articles
Page :