Checking if an element has a class in vanilla JavaScript
Feb 13, 2020 · Updated: Jun 24, 2026 · by Tim Kamanin
Let's say we have an element:
<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.
-
Grab the element from the DOM:
const button = document.querySelector("button"); -
Use the
element.classList.containsmethod to check for the class:// 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!
Hey, if you've found this useful, please share the post to help other folks find it: