Categories
JavaScript Answers

How to check if an element with the given ID has focus with JavaScript?

Spread the love

Sometimes, we want to check if an element with the given ID has focus with JavaScript.

In this article, we’ll look at how to check if an element with the given ID has focus with JavaScript.

How to check if an element with the given ID has focus with JavaScript?

To check if an element with the given ID has focus with JavaScript, we can check if document.activeElement is the same element as the element with the given ID.

For instance, we write

const dummyEl = document.getElementById("myID");
const isFocused = document.activeElement === dummyEl;

to get the element with ID myID with getElementById.

Then we check if dummyEl is focused with

document.activeElement === dummyEl

Conclusion

To check if an element with the given ID has focus with JavaScript, we can check if document.activeElement is the same element as the element with the given ID.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *