# Check if an element is focused

Compare the element with document.activeElement.

Canonical: https://1loc.dev/dom/check-if-an-element-is-focused/
Version: 1.0.0
Runtime: JavaScript · modern browsers (DOM)
Verification: Usage lines executed in headless Chromium against the fixture markup; no external services
Updated: 2026-10-28

## Implementation

```javascript
function hasFocus(element) { return element === document.activeElement; }
```

## Usage

Markup:

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

Script:

```javascript
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.

## 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 does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/check-if-an-element-is-focused.mdx
Source file (this edition): https://github.com/akamind/1loc/blob/0a77f131b22d2ba3b7ec1728846f900c22821678/contents/check-if-an-element-is-focused.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
