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.
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub or Twitter.
Renders the given DOM tree in the specified DOM element.
JavaScript, Browser · Oct 13, 2021
30 seconds of code uses cookies to provide a high quality user experience and gather anonymized data for statistical analysis of the website's traffic. You can learn more by reading our cookie policy. By clicking Accept you accept their installation.