snippetjavascriptTip
Select the focused DOM element with JavaScript
Viewed 0 times
domjavascriptelementfocusedwiththeselect
Problem
Finding the currently focused DOM element is trivial in modern CSS, using the
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.
: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 elementCode Snippets
const focusedElement = document.activeElement;
// `focusedElement` is the currently focused elementContext
From 30-seconds-of-code: select-focused-dom-element
Revisions (0)
No revisions yet.