How to add class names to a DOM element using JavaScript?

September 6, 2020 - 1 min read

Add class names to a DOM element

To add a class name to a DOM element, you can use the add() method in the classList property in an element using JavaScript.

Let's say you want to add a class name called red to an h1 element.

// first get the reference to the h1 element
const h1 = document.querySelector("h1");

// add red class name to h1 element
h1.classList.add("red");
  • The method accepts valid class names as arguments.

If you want to add multiple classes at the same time, you can pass those class names to the add() method by passing them as arguments like this,

// first get the reference to the h1 element
const h1 = document.querySelector("h1");

// add red, border-red, bg-yellow classnames
// to the h1 element at the same time
h1.classList.add("red", "border-red", "bg-yellow");

See this live example in JSBin.

Feel free to share if you found this useful 😃.