HTML DOM

HTML DOM activeElement Property

The activeElement property of the document object returns the currently focused element in the document - for example, the input, button, or link the user is interacting with.


Definition and Usage

document.activeElement returns a reference to the element that currently has focus. If no element has focus, it returns the <body> element (or the document's root element in some cases). It is a read-only property.

Syntax

document.activeElement

It takes no arguments and returns the focused Element object.

Example

Report the tag name of the focused element
<input type="text" id="name" placeholder="Click me">
<button onclick="showFocused()">Which element is focused?</button>
<p id="out"></p>

<script>
function showFocused() {
  const active = document.activeElement;
  document.getElementById("out").innerHTML =
    "Focused tag: " + active.tagName;
}
</script>

When you click into the text field and then click the button, the browser reports the element that held focus. Note that clicking the button moves focus to it, so activeElement reflects the element focused at the moment the code runs.

ℹ️

activeElement is useful for accessibility and keyboard-navigation code, where you need to know or restore which control the user was on.

Ready to use your HTML skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships