# Check if an element contains a CSS class in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Mar 5, 2020, updated Oct 15, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-check-if-element-contains-css-class

> Learn how to check if any HTML element contains a specific CSS class in vanilla JavaScript.

In JavaScript, you can use the `contains()` method provided by the [`classList`](https://attacomsian.com/blog/javascript-add-remove-toggle-css-classes#contains-method) 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:

```markup
<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](https://attacomsian.com/blog/getting-dom-elements-javascript):

```javascript
const button = document.querySelector('button')
```

Next, use the `classList.contains()` method to verify whether the element contains the `disabled` class:

```javascript
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](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Polyfill) 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`](https://attacomsian.com/blog/javascript-add-remove-toggle-css-classes#using-classname-property) property to check whether the class exists or not:

```javascript
// 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](https://attacomsian.com/blog/ways-to-check-string-contains-substring-javascript) name.
