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


HTML



Edit in JSFiddle

 
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


HTML



Edit in JSFiddle

 
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


HTML



Edit in JSFiddle

 
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:

That’s all about determining whether an element is present in DOM with JavaScript.