Check if specific Class exists on the Page using JavaScript


Borislav Hadzhiev

Sun Jan 02 20221 min read

Check if specific Class exists on the Page using JS #

To check if specific class exists on the page:

  • Use the document.getElementsByClassName() method to select the elements with the class name.
  • Check if the length property of the collection is greater than 0.
  • If it is, then the class exists on the page.

Here is the HTML for the examples in this article.

<!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.

const classExists = document.getElementsByClassName( 'box' ).length > 0; if (classExists) { console.log('✅ class exists on page'); } else { console.log('⛔️ class does NOT exist on page'); }

We used the document.getElementsByClassName to select all of the DOM elements with class name of box.

The method returns an HTMLCollection containing the elements with the specific class.

const boxes = document.getElementsByClassName('box'); console.log(boxes); // 👉️ []

If no elements in the DOM with the provided class exist, the method returns an empty HTMLCollection.

const boxes = document.getElementsByClassName('does-not-exist'); console.log(boxes); // 👉️ []
To see if there are any elements in the collection, we accessed the length property on the array-like object.

If the length of the HTMLCollection returns a value greater than 0, then the provided class exists on the page.

If the length property returns a value of 0, then the provided class does not exist on the page.

The classExists variable stores a boolean result:

  • true if the class exists on the page
  • false if the class does not exist on the page
Use the search field on my Home Page to filter through my more than 1,000 articles.