Categories
JavaScript Answers

How to change an element’s class with JavaScript?

Spread the love

Sometimes, we want to change an element’s class with JavaScript.

In this article, we’ll look at how to change an element’s class with JavaScript.

How to change an element’s class with JavaScript?

To change an element’s class with JavaScript=, we use the classList methods.

For instance, we write

document.getElementById("MyElement").classList.add("MyClass");
document.getElementById("MyElement").classList.remove("MyClass");
document.getElementById("MyElement").classList.toggle("MyClass");

to select the element with getElementById.

Then we call classList.add to add MyClass to the element.

We call classList.remove to remove MyClass from element.

And we call classList.toggle to toggle MyClass on the element.

Conclusion

To change an element’s class with JavaScript=, we use the classList 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 *