HTML DOM
HTML DOM activeElement Property
The activeElement property returns the element that currently has focus in the document. It is read-only and is most often used to find out which input, button, or link the user is interacting with.
Definition and Usage
document.activeElement returns a reference to the element in the DOM that currently receives keyboard input - typically a text field, button, textarea, or any element with focus. If no element is focused, it returns the <body> element (or the root element in some cases).
The property is read-only. To move focus programmatically you call the focus() method on an element; activeElement then reflects that change.
Syntax
document.activeElementExample
Click into either field, then press the button to see which element was focused just before. The tag name and id of the active element are shown in the output box.
<!DOCTYPE html>
<html>
<body>
<input id="name" placeholder="Your name">
<input id="email" placeholder="Your email">
<button onclick="show()">Which field is active?</button>
<div id="out" style="margin-top:12px;font-weight:bold;"></div>
<script>
function show() {
const el = document.activeElement;
document.getElementById("out").textContent =
"Active element: <" + el.tagName.toLowerCase() + "> id=" + (el.id || "none");
}
</script>
</body>
</html>More Examples
This demo updates continuously: as you move focus between the fields, the label reports the active element in real time using the focusin event.
<!DOCTYPE html>
<html>
<body>
<input id="a" placeholder="Field A">
<input id="b" placeholder="Field B">
<input id="c" placeholder="Field C">
<p id="out">Click a field to begin.</p>
<script>
document.addEventListener("focusin", function () {
document.getElementById("out").textContent =
"Focused: " + document.activeElement.id;
});
</script>
</body>
</html>When the page first loads and nothing has been clicked, document.activeElement usually points at the <body> element, not null.
Key Takeaways
- activeElement returns the element that currently has focus.
- It is a read-only property of the document object.
- It falls back to <body> when nothing is focused.
- Combine it with the focusin event to track focus changes live.
