How to find which DOM element has the focus using jQuery?
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:
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:
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
- Before clicked/focused:
- After clicked/focused:
- When input field is clicked/focused
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.