In JavaScript, you can use the contains()
method provided by the classList
object to check if any element contains a specific CSS class. This method returns true
if the class exists. Otherwise, false
is returned.
Let us say we have the following HTML element:
<button class="primary disabled">Subscribe Now</button>
And we want to check if the <button>
tag contains the disabled
class. The first step is to grab a reference to the element from the DOM:
const button = document.querySelector('button')
Next, use the classList.contains()
method to verify whether the element contains the disabled
class:
if (button.classList.contains('disabled')) {
console.log('Yahhh! Class is found.')
} else {
console.log('Class does not exist.')
}
The classList.contains()
method works in all modern browsers, and there are polyfills available to support old browsers up to Internet Explorer 6.
Alternatively, if you want to support old browsers without using any polyfill, use the element's className
property to check whether the class exists or not:
// convert `class` attribute into string tokens
const tokens = button.className.split(' ')
// check if the tokens array contains the `disabled` class
if (tokens.indexOf('disabled') !== -1) {
console.log('Yahhh! Class is found.')
} else {
console.log('Class does not exist.')
}
In the above code, we first split the className
property value, which refers to the class
attribute, into string tokens. Later, we use the indexOf()
method on the tokens
array to check if it contains the disabled
value.
You might be thinking why not simply use the button.className.indexOf('disabled') !== -1
statement? The problem is it will return true
even if the class you are looking for is part of another class name.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.