Wednesday, July 3, 2024
HomeLanguagesJavascriptHow to find which DOM element has the focus using jQuery?

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:

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:

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments