activeElement Reports The Focused Control
focus() and blur() update document.activeElement immediately, blur falls back to body, and document.hasFocus() reports whether the page owns the keyboard.
Code
document.body.innerHTML = `
<form>
<input id="email" />
<button id="send">Send</button>
</form>
`;
const email = document.querySelector("#email");
const send = document.querySelector("#send");
email.focus();
console.log(document.activeElement === email); // true
// blur() hands focus back to the page itself
email.blur();
console.log(document.activeElement.tagName); // BODY
// Focusing another control updates activeElement immediately
send.focus();
console.log(document.activeElement.id); // send
// hasFocus() asks whether this document owns the keyboard
console.log(document.hasFocus());How it works
Demo state sits in top-level bindings: email, send.
Points of care
- The import surface (if any) is all standard library, all versioned with the language itself.
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Key statements
const email = document.querySelector("#email");
const send = document.querySelector("#send");
<button id="send">Send</button>
</form>
`;
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does activeElement Reports The Focused Control run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.