Adding, Removing & Toggling Classes With classList in JavaScript

It’s much easier than it used to be to modify classes on an element, thanks in large part to the classList object.

Say we have an element like this:

<div class="cool new shades">

Let’s play around with the classes on that element. First, let’s grab a reference to the element in a shadesEl variable:

let shadesEl = document.querySelector('.cool');

// ["cool", "new", "shades", value: "cool new shades"]

console.log(shadesEl.classList[1]); // new

This works, but we should instead call one of the following methods on the classList object:


Add one or more classes to the element:

shadesEl.classList.add('make', 'me', 'look', 'rad');

Our element now:

<div class="cool new shades make me look rad">


Contains returns a boolean indicating if the class is present:

console.log(shadesEl.classList.contains('look')); // true


Get the class that’s at the provided index:

console.log(shadesEl.classList.item(3));  // make


Remove one of more classes:

shadesEl.classList.remove('cool', 'make', 'me');
<div class="new shades look rad">

JavaScript won't complain if you try to remove a class that doesn't exist.


Instead of doing a whole dance like this if you want to toggle a class on or off:

// Tedious toggle
if (shadesEl.classList.contains('rad')) {
} else {

…you can simply use classList.toggle instead. Say something like this on a button click:

coolButton.addEventListener('click', () => {

classList.toggle will return true if the class was added and false if it was removed:

let a = shadesEl.classList.toggle('cool');

console.log(a); // true --> class was added

classList.toggle optionally takes a second argument that should evaluate to a boolean. This will force toggle to either add the class or remove it depending on the how the second argument evaluates:

let someCondition;

let b = shadesEl.classList.toggle('cool', !!someCondition);
// false, `someCondition` is undefined and evaluates to false, class is removed

someCondition = 'I wear my sunglasses at night';

let c = shadesEl.classList.toggle('cool', !!someCondition);
// true, `someCondition` evaluates to true, class is added.

Using !! in front of an expression coerces the value to a boolean.

🤠 And that's it! It doesn't get any easier than this.

✖ Clear

🕵 Search Results

🔎 Searching...