Categories
JavaScript Answers

How to find if element with specific ID exists or not with JavaScript?

Spread the love

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.

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 *