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 call the setAttribute method.

For instance, we write

const [root] = document.getElementsByTagName("html");
root.setAttribute("class", "myCssClass");

to call getElementsByTagName to get the html elements in a node list.

Then we get the first one by destructuring.

Next we call setAttribute to set the 'class' attribute to 'myCssClass'.

Conclusion

To add class to html element with JavaScript, we call the setAttribute method.

Leave a Reply

Your email address will not be published. Required fields are marked *