For more tips like this, sign up to the weekly newsletter!

Use classList to manipulate classes

Working with the DOM often entails changing elements' classes. For example, to highlight a drop area during dragging.

A traditional way is to use the className property and directly set the list of classes using regexes and other magic to implement add/remove/toggle functionality. But if you decide to go this way, you soon encounter the many edge cases.

Instead of using a library to do the heavy lifting, use the classList property.

To add a class to an element:

e.classList.add(className);

It also supports multiple classes at once.

To remove a class (also supports multiple):

e.classList.remove(className);

To check if a class is present in the list:

e.classList.contains(className);

And finally, to toggle a class:

e.classList.toggle(className);

Multiple elements

Unlike jQuery's addClass/removeClass/toggleClass, classList does not support manipulating multiple elements at once. To achieve the same, iterate over all the elements explicitly:

document.querySelectorAll(...).forEach((e) => e.classList.add(className))

Browser support

According to caniuse, all current browsers support classList. Hooray!

Try it
References
Learn more: