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.

JavascriptData Integrity

Code

javascriptsnippet
23 lines
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

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.