How to add class

Learn how to add class names to elements using JavaScript.

Click the button to add the class for me!

Add class

Step 1 - Add HTML:

Add the class name to id="myDIV" the div element (in this example, we use a button to add the class).

<button onclick="myFunction()">Try it</button>
<div id="myDIV">
  This is a DIV element.
</div>

Step 2 - Add CSS:

Set the style of the specified class name:

.mystyle {
  width: 100%;
  padding: 25px;
  background-color: coral;
  color: white;
  font-size: 25px;
}

Step 3 - Add JavaScript:

obtain id="myDIV" the <div> element, and add "mystyle" Class:

function myFunction() {
  var element = document.getElementById("myDIV");
  element.classList.add("mystyle");
}

Try it yourself

Related pages

Tutorial:How to Toggle Class

Tutorial:How to Remove Class

Reference manual:HTML DOM Element classList Property

Reference manual:HTML DOM Element className Property