How to remove a class from a DOM element

By

Learn how to remove a class from a DOM element using the classList.remove() method, and how to add one with classList.add(), since classList is read-only.

~~~

When you have a DOM element reference you can remove a class using the remove method of classList:

const modal = document.querySelector('.modal')
modal.classList.remove('open')

You can remove multiple classes in one call:

modal.classList.remove('open', 'visible')

If the element doesn’t have that class, nothing happens. No error, no side effects. You don’t need to check with contains() before removing.

You can add a new class to it by using the add method:

modal.classList.add('open')

When toggle() is a better fit

Often you remove a class in one branch and add it in another, like opening and closing a menu. toggle() does both in a single call:

menu.classList.toggle('open')

It removes the class if present, adds it if missing, and returns true when the class ends up on the element.

You can also force a direction with the second argument:

menu.classList.toggle('open', false) //always removes

How to remove all classes at once

classList has no method for this, but you can clear the className property:

modal.className = ''

or remove the attribute entirely:

modal.removeAttribute('class')

Both leave the element with no classes. Use this rarely, since it also wipes classes other code might rely on.

Implementation detail: classList is not an array, but rather it is a collection of type DOMTokenList.

You can’t directly edit classList because it’s a read-only property. You can however use its methods to change the element classes.

remove() matches exact names only

Here’s the pitfall to know. remove() works on whole class names, not on prefixes or fragments:

button.classList.remove('btn')

This does nothing to an element with class btn-primary. The token btn doesn’t match btn-primary, so the class stays.

If you need to strip a family of prefixed classes, loop over classList and remove the matching ones. And as with add(), passing a string with a space like 'open visible' throws an exception. Pass the names as separate arguments instead.

~~~

Related posts about platform: