Checking if an element has a class in vanilla JavaScript

13 Feb · by Tim Kamanin · 1 min read

Let's say we have an element:

html
<button class="primary active">Click me</button>

And we want to check if the element has the active class.

Here's how to do this in two simple steps.

1. Grab the element from the DOM:

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

2. Use element.classList.contains method to check for a class:

javascript
// returns 'true' if the class exists, and 'false' if it doesn't.
const isActive = button.classList.contains('active');

It's really as simple as that!

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials