Check if an Element does NOT have specific Class using JS

avatar

Borislav Hadzhiev

Last updated: Jan 2, 2022

banner

Check out my new book

Check if an Element does NOT have specific Class using JS #

Use the classList.contains() method to check if an element does not have a specific class, e.g. if (!el.classList.contains('my-class')) {}. If the element does not have the provided class, the method returns false, otherwise true is returned.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .bg-salmon { background-color: salmon; } </style> </head> <body> <div id="box" class="bg-salmon">Box 1</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); if (!box.classList.contains('bg-salmon')) { console.log('Element does NOT have class'); } else { console.log('Element has class'); }

We used the classList.contains method to check if the element does not have a class name.

The contains() method returns true if the element has the provided class and false otherwise.

index.js
const box = document.getElementById('box'); // 👇️ true console.log(box.classList.contains('bg-salmon')); // 👇️ false console.log(box.classList.contains('does-not-exist'));

We used the logical NOT (!) operator to negate the result returned from the contains() method.

When used with boolean values, like in the example, the operator flips the value, e.g. true becomes false and vice versa.

index.js
console.log(!true); // 👉️ false console.log(!false); // 👉️ true

If the element does not contain the bg-salmon class, our if block runs, otherwise the else block runs.

index.js
const box = document.getElementById('box'); if (!box.classList.contains('bg-salmon')) { console.log('Element does NOT have class'); } else { console.log('Element has class'); }

Note that if you are checking if certain class is not present because you don't want to add it twice, you can use the classList.add() method to avoid this scenario.

index.js
const box = document.getElementById('box'); // ✅ Add classes to element box.classList.add('first-class', 'second-class'); // ✅ Remove classes from element box.classList.remove('third-class', 'fourth-class');
The classList.add() method adds one or more classes to an element. If any of the provided classes already exists on the element, the class is omitted.

The classList.remove() method removes one or more classes from the element. If the class does not exist on the element, the method ignores the class and does not throw an error.

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