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.