Sometimes, we want to add class to html element with JavaScript.
In this article, we’ll look at how to add class to html element with JavaScript.
How to add class to html element with JavaScript?
To add class to html element with JavaScript, we can use the classList.add method.
For instance, we write
const [root] = document.getElementsByTagName("html");
root.classList.add("myCssClass");
to select all html elements with getElementsByTagName, get the first one, and assign it to root.
Then we call root.classList.add to 'myCssClass' to add the myCssClass class to the html element.
Conclusion
To add class to html element with JavaScript, we can use the classList.add method.