To change an element's class with JavaScript, you can use the className property to set the class to a new value.
Here is an example of how you might change the class of an element with the id "example-element" to "new-class":
document.getElementById("example-element").className = "new-class";
Alternatively, you can use the classList property to add or remove classes from an element. Here is an example of how you might add a class "new-class" to an element with the id "example-element":
document.getElementById("example-element").classList.add("new-class");
And here is an example of how you might remove a class "old-class" from an element with the id "example-element":
document.getElementById("example-element").classList.remove("old-class");
You can also toggle a class on an element using classList.toggle.
document.getElementById("example-element").classList.toggle("new-class");
It's worth noting that the above examples use getElementById method to select the element. You can select elements using other methods such as querySelector, querySelectorAll, getElementsByClassName, getElementsByTagName etc.
Comments (0)