What is the HTML activeElement property?
In this shot, we will learn how to get the active element of the HTML page. The HTML DOM property document.activeElement helps us find the active element.
Active Elements are the HTML elements that have recently been focused on by the user. If a user clicks on a button that means the button was focused or it was active.
Syntax
var element = document.activeElement;
Return value
The document.activeElement property will return the HTML element object that was focused.
Code
We will try to display the active element of the HTML page using the document.activeElement property.
Explanation
-
In lines 4 to 9, we defined a function named
myFunction()in the<script>tag. -
In line 6, we used the HTML DOM property
document.activeElementto get the reference of the active element (which is recently or currently in focus). Focus means you have last element you have used or clicked. The returned object has several attributes; one of them istagName, which holds the name (type) of element and assigns it to thexvariable. -
In line 7, using
innerHTMLto change the text in the<p>tag with iddemo, within which we assign the value we stored in variablex.