Borislav Hadzhiev
Sun Jan 02 2022·1 min read
Photo by Nicolas Prieto
To check if specific class exists on the page:
document.getElementsByClassName()
method to select the elements with
the class name.length
property of the collection is greater than 0
.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); // 👉️ [div.box]
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); // 👉️ []
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 pagefalse
if the class does not exist on the page