Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to add and remove multiple CSS classes to an element with JavaScript.

In this article, we’ll look at how to add and remove multiple CSS classes to an element with JavaScript.

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

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

For instance, we write

buttonTop.classList.add("myButton", "myStyle");

to call classList.add on the buttonTop element to add the myButton and myStyle classes.

And we write

buttonTop.classList.remove("myElement", "myButton", "myStyle");

to call classList.add on the buttonTop element to remove the myElement, myButton and myStyle classes.

Conclusion

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

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 *