Sometimes, we want to find if element with specific ID exists or not with JavaScript.
In this article, we’ll look at how to find if element with specific ID exists or not with JavaScript.
How to find if element with specific ID exists or not with JavaScript?
To find if element with specific ID exists or not with JavaScript, we check if getElementById
returns the element or null
.
For instance, we write
const myEle = document.getElementById("myElement");
if (myEle) {
const myEleValue = myEle.value;
}
to get the element with getElementById
.
And then we get the value
property of myEle
if it’s not null
.
Conclusion
To find if element with specific ID exists or not with JavaScript, we check if getElementById
returns the element or null
.