How to check if a DOM element has a class
By Flavio Copes
Learn how to check if a DOM element has a class using the contains method of the classList object, which implements the DOMTokenList interface.
To check if a DOM element has a class, use the contains method provided by the classList object:
element.classList.contains('myclass')
It returns true if the class is there, false if not.
Here’s a complete example. Say we have a button and we want to know if it’s currently marked as active:
const button = document.querySelector('.subscribe-button')
if (button.classList.contains('active')) {
console.log('already active')
}
Technically, classList is an object that satisfies the DOMTokenList interface, which means it implements its methods and properties.
You can see its details on the DOMTokenList MDN page.
In practice this means classList sees the class attribute as a list of separate tokens, not one big string. An element with class="btn btn-large active" has three entries in its classList, and contains() checks each of them for an exact match.
Names are case sensitive: contains('Active') returns false if the class is active.
Why not check className directly?
Before classList, the common way was to look at the className string:
button.className.includes('active')
This has a bug. className is the raw attribute value, so includes() matches substrings. If the element has the class inactive, the check for 'active' returns true, because “active” appears inside “inactive”.
classList.contains() compares whole class names, so it doesn’t have this problem. That’s the fix: always go through classList for class checks.
The other classList methods
Once you’re checking classes, you usually want to change them too. classList covers that:
button.classList.add('active')
button.classList.remove('active')
button.classList.toggle('active')
toggle() is handy because it removes the class if present and adds it if missing, and it returns true when the class ends up on the element. A common pattern is checking and toggling in one step:
const isOpen = menu.classList.toggle('open')
One last note: classList reflects the live state of the element. If some other code adds or removes classes, the next contains() call sees the current classes, not the ones the element started with.
Related posts about platform: