How to add and remove multiple CSS classes to an element with JavaScript?

Spread the love

To add and remove multiple CSS classes to an element with JavaScript, we use the classList.add and classList.remove methods.

For instance, we write

const [el] = document.getElementsByClassName("myclass");

el.classList.add("newclass");

el.classList.remove("newclass");

to select the first element with class myclass with getElementsByClassName and destructuring.

And then we call classList.add to add the newclass class to element el.

We call classList.remove to remove the newclass class from element el.

Leave a Reply

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