Check if an element is focused
Compare the element with document.activeElement.
function hasFocus(element) { return element === document.activeElement; }
Usage
Markup
<label>Email <input id="email" type="email"></label>
<button id="submit">Subscribe</button>
Script
const email = document.querySelector('#email');
email.focus();
hasFocus(email); // → true
hasFocus(document.querySelector('#submit')); // → false
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.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.