In this section, we will learn what the document activeElement property is and how to use it in JavaScript.
What is document activeElement Property in JavaScript?
The JavaScript document activeElement property is used to get the currently activated element in a document.
For example, you might have a text-box for username in a document, and that has already the focus (for example a user is typing her username in the box). So calling this property will return a reference to this text-box element on the page.
document activeElement Property Syntax:
document.activeElement
document activeElement Property Input value.
This property is read-only and so it doesn’t take input.
document activeElement Property Return Value
The return value of the activeElement property is a reference to an element in the page that currently has the focus.
Example: using document activeElement Property in JavaScript
See the Pen using document activeElement Property in JavaScript by Omid Dehghan (@odchan1) on CodePen.
How Does document activeElement property work?
In this example, any time we click on the page or on any element, the onclick event for the body element triggers a call to `myFunction`. Inside this function we call the activeElement property to get the tag name of the currently focused element in page and alert its name to the user.