Check if an element contains a CSS class in JavaScript

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.