Skip to main content Accessibility Feedback

How to add and remove classes with vanilla JS

The Element.classList API provides methods that you can use to add(), remove(), toggle() and check if an element contains() a class or classes.

let elem = document.querySelector('#sandwich');

// Add the .turkey class
elem.classList.add('turkey');

// Remove the .tuna class
elem.classList.remove('tuna');

// Toggle the .tomato class on or off
// (Add the class if it's not already on the element, remove it if it is.)
elem.classList.toggle('tomato');

// Check if an element has the .mayo class
if (elem.classList.contains('mayo')) {
	console.log('add mayo!');
}

Here’s a demo.

One lesser known feature of the Element.classList API is that you can also use it to add or remove multiple classes from element. Pass the classes to add or remove into the respective method as a comma separated list.

// Add the .turkey and .mayo classes
elem.classList.add('turkey', 'mayo');

// Remove the .tuna and .tomato classes
elem.classList.remove('tuna', 'tomato');

Here’s another demo.

If you have an array of classes, you can use array destructuring to pass in all of the classes as individual items.

let classNames = ['turkey', 'mayo'];
elem.classList.add(...classNames);

Here’s one last demo.