How to check if an element contains a CSS class in JavaScript

published: 15 Jun 2022

2 min read

Check if an element contains a CSS class in JavaScript

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

How to check if an element contains a CSS class in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, array