Check if specific Class exists on the Page using JavaScript

avatar

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.

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

index.js
const boxes = document.getElementsByClassName('box'); console.log(boxes); // ๐Ÿ‘‰๏ธ [div.box]

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

index.js
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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee