How To Add Class To Html Element With JavaScript? - The Web Dev

Skip to the content Close Menu
  • HTML
  • CSS
  • JavaScript
  • Python
  • Contact
  • About the Site
  • About the Author
Labrador retriever puppy walking on green grass
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.

Related Posts

  • How to get only first class of an HTML element with JavaScript?

    Sometimes, we want to get only first class of an HTML element with JavaScript. In…

  • How to add or update an attribute to an HTML element using JavaScript?

    Sometimes, we want to add or update an attribute to an HTML element using JavaScript.…

  • How to Add Options to an HTML select Element with JavaScript?

    Sometimes, we want to add options to an HTML select element with JavaScript. In this…

By John Au-Yeung

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

View Archive How to get city name from a latitude and longitude point with JavaScript? How to sort an ES6 Set with JavaScript?

Leave a Reply Cancel reply

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

Comment *

Name *

Email *

Website

Save my name, email, and website in this browser for the next time I comment.

Current ye@r * Leave this field empty

Tag » Add Class To Html Element Js