Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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

Syntax:

let ele = document.activeElement;

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

Example Code Snippets:

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

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

Sample Code to demonstrate working: 

HTML




<!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 () {
            let x = document.activeElement.tagName;
            document.getElementById("fun").innerHTML = x;
        });
    </script>
</body>
   
</html>


Explanation: The script inside the 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 that is returned by the

document.activeElement.tagName

Output:

 


Last Updated : 21 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads