Tip: Select the focused DOM element

JavaScript, Browser · Oct 23, 2022

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.

More like this

  • Tips & Tricks

    A collection of quick tips and tricks to level up your coding skills one step at a time.

    Collection · 53 snippets

  • Element is focused

    Checks if the given element is focused.

    JavaScript, Browser · Oct 19, 2020

  • Tip: You can get the value of an input element as a number

    Ever wanted to get the value of an HTML input element as a number? Learn an easy way to do it with this handy trick.

    JavaScript, Browser · Jun 12, 2021

  • Render DOM element

    Renders the given DOM tree in the specified DOM element.

    JavaScript, Browser · Oct 13, 2021