Categories
JavaScript Answers

How to add class to html element with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.