How to add and remove multiple classes in JavaScript.
There are plenty of situations where we need to dynamically edit the class names of elements in our DOM. Sometimes there is no other option but to edit the class with JavaScript but if we want to add multiple classes at once the solution might not be obvious initially.
So, how can you add and remove multiple classes in JavaScript? There are 3 main ways to add and remove multiple classes:
- Using the
classList
method add or remove multiple classesclassList.add
for addingclassList.remove
for removing
- Using the
spread operator
to add multiple classes in an array - Using the plus operator to add to the current class list
ClassList
Using classList, let’s say we have an element like so:
const el = document.getElementsByClassName('metaClass')
To add multiple classes:
el.classList.add("wrapper", "nested", "child");
To remove multiple classes:
el.classList.remove("wrapper", "nested", "child");
Spread Operator
We can use the spread operator to add multiple classes like so
let classesToAdd = ["wrapper", "nested", "child"]; el.classList.add(...classesToAdd);
Plus Operator
To add multiple classes using the plus operator:
el.className += " wrapper nested";
And there we have it, three ways to add or remove multiple classes in JavaScript.