Files
30-seconds-of-code/blog_posts/select-focused-dom-element.md
Angelos Chalaris da31e8d138 Update covers
2023-02-16 22:24:41 +02:00

932 B

title, shortTitle, type, tags, author, cover, excerpt, firstSeen
title shortTitle type tags author cover excerpt firstSeen
Tip: Select the focused DOM element Focused DOM element tip javascript,browser chalarangelo horse-sunset Here's a quick and easy way to select the currently focused DOM element in JavaScript. 2022-10-23T05:00:00-04:00

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.

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

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.