Last updated: Mar 5, 2024
Reading timeยท2 min

Use the classList.contains() method to check if an element does not have a
specific class.
If the element does not have the provided class, the method returns false,
otherwise true is returned.
Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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.
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.
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.
console.log(!true); // ๐๏ธ false console.log(!false); // ๐๏ธ true
If the element doesn't contain the bg-salmon class, our if block runs,
otherwise, the else block runs.
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 a 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.
const box = document.getElementById('box'); // โ Add classes to the element box.classList.add('first-class', 'second-class'); // โ Remove classes from the element box.classList.remove('third-class', 'fourth-class');
classList.add() method adds one or more classes to an element. If any of the provided classes already exist 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.