Categories
JavaScript Answers

How to Add or Remove Several Classes in One Single Instruction with classList?

Spread the love

Sometimes, we want to add or remove several classes in one single instruction with the classList API.

In this article, we’ll look at how to add or remove several classes in one instruction with classList .

Add or Remove Several Classes in One Single Instruction with classList

The add method takes one or more class name strings.

Therefore, we can use it to add more than one class at a time.

For instance, if we have the following HTML:

<div>

</div>

Then we can add more than one class by writing:

const div = document.querySelector('div')
div.classList.add("first", "second", "third");

If we have an array, then we can spread the entries as arguments:

const div = document.querySelector('div')
const list = ['first', 'second', 'third'];
div.classList.add(...list);

And we can replace the spread operator with apply :

const div = document.querySelector('div')
const list = ['first', 'second', 'third'];
div.classList.add.apply(
  div.classList,
  list
);

Set the className Property

We can also set the className property to a string with multiple classes with each separated by a space.

For instance, we can write:

const div = document.querySelector('div')
const list = ['first', 'second', 'third'];
div.className += list.join(' ');

to do the same thing.

The existing classes will be overwritten.

Conclusion

We can use the classList.add method or set the className property to add multiple class names to an element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *