Check if an element is focused

Compare the element with document.activeElement.

JavaScriptBrowser · DOM Version 1.0.0 · MIT · .md

check-if-an-element-is-focused.js
function hasFocus(element) { return element === document.activeElement; }

Usage

Markup

fixture.html
<label>Email <input id="email" type="email"></label>
<button id="submit">Subscribe</button>

Script

usage.js
const email = document.querySelector('#email');
email.focus();
hasFocus(email); // → true
hasFocus(document.querySelector('#submit')); // → false

Lines marked → were executed in headless Chromium against the markup above, and each result was compared with the value shown. Lines marked e.g. are illustrative.

Know the limits

  • Inside shadow DOM, document.activeElement is the shadow host; element.matches(":focus") checks the element itself.
  • activeElement stays set while the window is in the background; document.hasFocus() says whether the page itself has focus.

The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.

Source & maintenance

Based on Check if an element is focused from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.

Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/check-if-an-element-is-focused.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.

Usage lines executed in headless Chromium against the fixture markup; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.