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
property.
For instance, we write
document.getElementById("MyElement").classList.add("MyClass");
document.getElementById("MyElement").classList.remove("MyClass");
if (document.getElementById("MyElement").classList.contains("MyClass")) {
//...
}
document.getElementById("MyElement").classList.toggle("MyClass");
to use classList.add
to add the MyClass
class.
We use classList.remove
to remove the MyClass
class.
And we use classList.contains
to check if the MyClass
class is in the element.
We use classList.toggle
to toggle the MyClass
class on the element.
Conclusion
To change an element’s class with JavaScript, we use the classList
property.