HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Select the focused DOM element with JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
domjavascriptelementfocusedwiththeselect

Problem

Finding the currently focused DOM element is trivial in modern CSS, using the :focus selector. You can also use it in JavaScript, in combination with Document.querySelector() to find the focused element. Yet, there's an even easier way to get the currently focused element in JavaScript, using the Document.activeElement property.
Note that focusable elements vary depending on browser and operating system. Additionally, you should remember that focus and selection (i.e. content highlighting) are not the same thing.

Solution

const focusedElement = document.activeElement;
// `focusedElement` is the currently focused element

Code Snippets

const focusedElement = document.activeElement;
// `focusedElement` is the currently focused element

Context

From 30-seconds-of-code: select-focused-dom-element

Revisions (0)

No revisions yet.