Check if a Div with specific Class exists using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 2, 2022

banner

Check out my new book

Check if a Div with specific Class exists using JavaScript #

To check if a div with specific class exists:

  1. Use the document.querySelectorAll() method to get a NodeList containing the div elements with the specific class.
  2. Use the length property on the NodeList to check if it contains any elements.
  3. If the length property returns a value greater than 0, the div element exists.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Box 1</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const divWithClassExists = document.querySelectorAll( 'div.box' ).length > 0; if (divWithClassExists) { console.log('✅ Div with class exists'); } else { console.log('⛔️ Div with class does not exist'); }

We used the document.querySelectorAll method to select the div elements with the class of box.

The method returns a NodeList containing the elements that match the selector.

index.js
const boxes = document.querySelectorAll('div.box'); console.log(boxes); // 👉️ [div.box]

If there are no elements that match the selector, the method returns an empty NodeList.

index.js
const boxes = document.querySelectorAll('div.does-not-exist'); console.log(boxes); // 👉️ []

We used the length property on the collection to check if the div with the specific class is contained on the page.

If the length property returns a value greater than 0, then the div with the specific class is contained in the DOM, otherwise it isn't.

The divWithClassExists variable stores a boolean value:

  • true if the div element with the specific class is contained in the DOM.
  • false if the div element with the class is not contained in the DOM.

If you need to check if any element with the specific class is contained in the DOM and not constraint the result to only div elements, you can adjust the selector we passed to the querySelectorAll method.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <span class="box">Box 1</span> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const elWithClassExists = document.querySelectorAll('.box').length > 0; if (elWithClassExists) { console.log('✅ Element with class exists'); } else { console.log('⛔️ Element with class does not exist'); }

If an element of any type with the class of box exists in the DOM the elWithClassExists variable will store a true value.

Use the search field on my Home Page to filter through my more than 3,000 articles.