In vanilla 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.

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, just 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 tokens array contains `disabled`
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 look for is part of another class name.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.