JavaScript Document activeElement Property

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance property

What You’ll Learn

The activeElement property is a read-only reference to the element in your document that is receiving keyboard events—usually the focused field or button. Learn how it differs from text selection, what MDN’s textarea demo shows, iframe and shadow-DOM edge cases, and five hands-on examples with try-it labs.

01

Kind

Instance property

02

Returns

Element

03

Means

Keyboard focus

04

vs

getSelection()

05

Move focus

element.focus()

06

Status

Baseline widely

Introduction

When a user tabs into a search box or clicks a button, that element becomes the active (focused) element. Keyboard shortcuts, typing, and Space/Enter activation go to whatever has focus.

document.activeElement tells you which element that is right now. It is one of the most practical Document properties for forms, modals, keyboard shortcuts, and accessibility tooling.

💡
Focus is not selection

Highlighted text in a textarea is selection. Use window.getSelection() for that. activeElement answers “which control has the caret?”

This page is part of the Document tutorials. Related topics include Event.target, ownerDocument, and focusin event.

Understanding Document.activeElement

A read-only instance property on the Document interface. It returns the deepest Element that currently has focus within this document.

  • Value — an Element (or occasionally document.body / document.documentElement when nothing else is focused).
  • Keyboard events — keydown/keyup are dispatched to the active element.
  • Tab navigation — pressing Tab moves focus among focusable controls; activeElement updates automatically.
  • Platform differences — on Safari/macOS, non-text controls may not be focusable until “Full Keyboard Access” is enabled in System Settings.
  • Cross-document focus — if focus is outside this document tree, the property may be null or point at a host such as an <iframe>.

📝 Syntax

JavaScript
document.activeElement

Value

The deepest focused Element. If no element has focus, browsers typically fall back to document.body or document.documentElement.

Typical patterns

JavaScript
// Read who has focus
const el = document.activeElement;
console.log(el.tagName, el.id);

// Move focus programmatically
document.getElementById("email").focus();
console.log(document.activeElement.id); // "email"

// Guard before acting on keyboard shortcuts
if (document.activeElement.matches("input, textarea")) {
  return; // do not steal keys while typing
}

⚡ Quick Reference

GoalCode / note
Read focused elementdocument.activeElement
Check tag / iddocument.activeElement.tagName
Move focuselement.focus()
Is it an input?activeElement.matches("input, textarea, select")
Text selectionwindow.getSelection() (not activeElement)
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about document.activeElement.

Type
Element

Read-only

Means
focus

Keyboard target

Fallback
body

When unfocused

Baseline
widely

Since Jul 2015

Examples Gallery

Examples follow MDN Document: activeElement. Use View Output or Try It Yourself for each case.

📚 Getting Started

Read the focused element after a user clicks or tabs.

Example 1 — Read document.activeElement

Click an input and log which element currently has focus.

JavaScript
const input = document.getElementById("search");
input.addEventListener("focus", () => {
  const active = document.activeElement;
  console.log(active.tagName); // "INPUT"
  console.log(active.id);      // "search"
});
Try It Yourself

How It Works

Whenever focus moves, document.activeElement updates to match the element receiving keyboard events.

Example 2 — MDN Textarea Selection Demo

On mouseup, read the active textarea and the selected substring.

JavaScript
function onMouseUp() {
  const activeTextarea = document.activeElement;
  const selection = activeTextarea.value.substring(
    activeTextarea.selectionStart,
    activeTextarea.selectionEnd
  );

  outputElement.textContent = activeTextarea.id;
  outputText.textContent = selection;
}

textarea1.addEventListener("mouseup", onMouseUp);
textarea2.addEventListener("mouseup", onMouseUp);
Try It Yourself

How It Works

activeElement identifies which field is focused. selectionStart / selectionEnd describe what text is highlighted inside it.

📈 Practical Patterns

Track focus changes, defaults, and programmatic moves.

Example 3 — Log Focus with focusin

One document-level listener reports every focus change.

JavaScript
document.addEventListener("focusin", () => {
  const active = document.activeElement;
  status.textContent =
    "Focused: " + active.tagName.toLowerCase() +
    (active.id ? "#" + active.id : "");
});
Try It Yourself

How It Works

focusin bubbles, so you can observe focus from one listener instead of wiring every control separately.

Example 4 — Default When Nothing Is Focused

On first load, inspect what the browser reports before the user interacts.

JavaScript
const active = document.activeElement;

console.log(active.tagName); // often "BODY" or "HTML"
console.log(active === document.body);
console.log(active === document.documentElement);
Try It Yourself

How It Works

There is always some active element in the document—often body until the user focuses a control.

Example 5 — Programmatic Focus with focus()

Move focus to a field and confirm with activeElement.

JavaScript
const email = document.getElementById("email");

openFormBtn.addEventListener("click", () => {
  email.focus();
  console.log(document.activeElement === email); // true
  console.log(document.activeElement.id);        // "email"
});
Try It Yourself

How It Works

You cannot assign document.activeElement. Call focus() on the element you want active, then read the property to verify.

🚀 Common Use Cases

  • Form UX — auto-focus the first invalid field after validation fails.
  • Modals — trap focus inside a dialog and restore focus on close.
  • Keyboard shortcuts — skip global handlers when the user is typing in an input.
  • Rich text / textarea tools — apply formatting to the focused field (MDN pattern).
  • Accessibility audits — log which control receives Tab order.
  • SPA routing — move focus to main content after navigation for screen readers.

🔧 How Focus Tracking Works

1

User or script moves focus

Tab, click, or element.focus() targets a focusable element.

Input
2

Browser updates active element

document.activeElement now references that node.

State
3

Keyboard events route here

Typing and Space/Enter activation go to the active element.

Events
4

Your code reads it

Branch on tag, id, or matches() to build keyboard-friendly UI.

📝 Notes

  • MDN: Baseline Widely available (since July 2015) — no Deprecated / Experimental / Non-standard banner.
  • Read-only — use element.focus() to change focus.
  • Focus ≠ selection — pair with getSelection() when you need highlighted text.
  • Shadow DOM / iframe trees may return a host element or null across document boundaries.
  • Safari on macOS may limit focus on non-text elements unless Full Keyboard Access is on.
  • Also exists on ShadowRoot.activeElement for shadow trees.

Universal Browser Support

Document.activeElement is marked Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline · Widely available

Document.activeElement

Read-only Element reference for keyboard focus — essential for forms, modals, shortcuts, and accessibility.

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium
Full support
Opera Full support · Modern versions
Full support
Internet Explorer Supported in legacy IE
Full support
Document.activeElement Excellent

Bottom line: Use document.activeElement to read focus, element.focus() to move it, and getSelection() when you need highlighted text — not the same thing.

Conclusion

document.activeElement is the standard way to ask “which element has focus right now?” Use it for forms, keyboard shortcuts, and focus management — and remember that text selection is a separate concept.

Continue with activeViewTransition, ownerDocument, Event.target, Document constructor, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Read document.activeElement when handling global keys
  • Call focus() to move focus programmatically
  • Use focusin / focusout for bubbling focus tracking
  • Restore focus after closing modals (save previous element first)
  • Guard shortcuts when activeElement is an editable field

❌ Don’t

  • Assign to document.activeElement
  • Confuse focus with getSelection() highlighted text
  • Assume every clickable element is focusable on every platform
  • Steal focus on every route change without an accessibility reason
  • Read activeElement from the wrong document (iframe vs parent)

Key Takeaways

Knowledge Unlocked

Five things to remember about activeElement

The read-only focus pointer on every Document.

5
Core concepts
📝02

Read-only

use focus()

Pattern
📋03

Selection

different API

Compare
🔍04

MDN demo

textarea id

Example
🎯05

Baseline

since Jul 2015

Status

❓ Frequently Asked Questions

It is a read-only Document property that returns the deepest Element currently receiving keyboard events (keydown, keyup, and similar). In most cases that is the same element that has focus.
No. MDN marks Document.activeElement as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
When no element has focus, activeElement is usually document.body or document.documentElement — depending on the browser and page.
No. Focus is which element receives keyboard input. Selection is the highlighted text range. Use window.getSelection() for selection; use activeElement for focus.
No. It is read-only. To move focus, call element.focus() on the target you want active.
If focus is in another document (for example the main page while your script runs inside an iframe), activeElement from the iframe document may be null. If focus is inside a shadow tree hosted in your document, you may get the shadow host (such as an iframe element) instead of the inner node.
Did you know?

The same property exists on shadow roots: shadowRoot.activeElement returns the focused element inside that shadow tree. On the light DOM document, focus inside closed or nested shadow trees may surface as the shadow host element instead of the inner node.

Next: activeViewTransition

Read the active document-scoped ViewTransition handle.

activeViewTransition →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful