How do I check if an element exists in the DOM in JavaScript?
Benjamin C
benjamin c profile pic

In JavaScript, there are multiple ways to check if an element exists in the DOM. Here are a few common approaches: 1. Usingdocument.querySelector() ordocument.getElementById(): - Thedocument.querySelector() method allows you to select elements from the DOM using CSS selectors. You can check if an element exists by attempting to select it and then verifying if the returned value is notnull. - Thedocument.getElementById() method specifically selects an element by its unique ID. If the element with the specified ID exists, it will be returned; otherwise,null will be returned.

1
2
3
4
5
6

   const element = document.querySelector('.my-element');
   if (element !== null) {
     // Element exists in the DOM
   }
   

1
2
3
4
5
6

   const element = document.getElementById('myElement');
   if (element !== null) {
     // Element exists in the DOM
   }
   

Here,document.querySelector('.my-element') selects the first element with the class'my-element', anddocument.getElementById('myElement') selects the element with the ID'myElement'. 2. Usingdocument.contains() orelement.contains(): - Thedocument.contains() method checks if an element is within the document object, while theelement.contains() method checks if an element is within another specific element. - These methods return a boolean value indicating whether the element is found.

1
2
3
4

   const element = document.querySelector('.my-element');
   const isElementInDocument = document.contains(element);
   

Here,document.contains(element) checks if theelement is present within the document. 3. Usingdocument.querySelector() ordocument.getElementById() with a truthy check: - When querying an element usingdocument.querySelector() ordocument.getElementById(), the returned value will be falsy (null) if the element does not exist. - Therefore, you can use this falsy check to determine if the element exists.

1
2
3
4
5
6

   const element = document.querySelector('.my-element');
   if (element) {
     // Element exists in the DOM
   }
   

1
2
3
4
5
6

   const element = document.getElementById('myElement');
   if (element) {
     // Element exists in the DOM
   }
   

In this example, the truthy checkif (element) evaluates totrue ifelement is notnull orundefined, indicating that the element exists. Choose the method that suits your specific use case and preference. The first two methods are more explicit, while the third method relies on the truthy/falsy nature of the returned value from the DOM query methods.