How to return the currently active elements in the HTML document ?
Last Updated :
28 Feb, 2022
In this article, we will discuss how to return the currently active element in an HTML document. We will use the activeElement DOM property which will help us to achieve so. The DOM activeElement property is used to return the currently active elements in the HTML document. This property is read-only. It provides us with a reference to a focused element object in the document.
Syntax:
document.activeElement
Example 1: In this example, we will return the tag name which is currently active.
HTML
<!DOCTYPE html>
< html lang = "en" >
< body onclick = "clickedActiveElement()" >
< center >
< h1 style = "color: green;" >
GeeksforGeeks
</ h1 >
< b >How to return the currently active
elements in the HTML document?
</ b >
< br />< br />
< input type = "text"
placeholder = "I am input" />
< br />< br />
< button >This is a button</ button >
< br />
< h2 id = "result" ></ h2 >
</ center >
< script >
function clickedActiveElement() {
// Get the active element
var isActive =
document.activeElement.tagName;
// Output the active element to the result
var element =
document.getElementById('result');
element.innerHTML =
"Active Element is: " + isActive;
element.style.color =
"green";
}
</ script >
</ body >
</ html >
|
Output:
Example 2: In this example, we will return the element id which is currently active.
HTML
<!DOCTYPE html>
< html lang = "en" >
< body id = "body-id" onclick = "clickedActiveElement()" >
< center >
< h1 style = "color: green;" >
GeeksforGeeks
</ h1 >
< b >How to return the currently active
belements in the HTML document?
</ b >
< br />< br />
< input type = "text"
placeholder = "I am input"
id = "input-text-id" />
< br />< br />
< input type = "checkbox"
id = "input-checkbox-id" />
CheckBox
< br />< br />
< button id = "button-id" >Button</ button >
< br />
< h2 id = "result" ></ h2 >
</ center >
< script >
function clickedActiveElement() {
// Get the active element's ID
var activeElementId =
document.activeElement.id;
// Output the ID to the result
var element =
document.getElementById('result');
element.innerHTML =
"Active Element is: " + activeElementId;
element.style.color =
"green";
}
</ script >
</ body >
</ html >
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...