Check whether an element is present in DOM with JavaScript
This post will discuss how to check whether an element is present in the DOM with JavaScript.
JavaScript offers several element-lookup methods to search for an element in DOM using its ID, name, class, or type. The standard method to get an element by its ID is getElementById(). To get the elements with a given name in the document, there is the getElementsByName() method. Similarly, to get all elements having the given class, you can use the getElementsByClassName() method. Following is a simple example demonstrating usage of the getElementById() method:
JS
|
1 2 3 4 5 6 |
if (document.getElementById("name") !== null) { alert("The element exists"); } else { alert("The element does not exist"); } |
HTML
|
1 |
<label>Email address: <input type="email" id="name" placeholder="Enter email"></label> |
JavaScript also has advanced lookup methods such as querySelector() and querySelectorAll() that can take one or more selectors to match against. Following is a simple example demonstrating the usage of the querySelector() method, which returns the first matching element within the document:
JS
|
1 2 3 4 5 6 |
if (document.querySelector("#name") !== null) { alert("The element exists"); } else { alert("The element does not exist"); } |
HTML
|
1 |
<label>Email address: <input type="email" id="name" placeholder="Enter email"></label> |
Unlike querySelector() method, querySelectorAll() returns a NodeList of all matching elements. Since NodeList is an object, you can check its length property to check for the returned elements count.
JS
|
1 2 3 4 5 6 |
if (document.querySelectorAll("#name").length) { alert("The element exists"); } else { alert("The element does not exist"); } |
HTML
|
1 |
<label>Email address: <input type="email" id="name" placeholder="Enter email"></label> |
Also, with the Node.contains() method, you can check if an element is in the page’s body. MDN already provides a utility method for it:
|
1 2 3 |
function isInPage(node) { return (node === document.body) ? false : document.body.contains(node); } |
That’s all about determining whether an element is present in DOM with JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)