How to add a class

Learn how to add a class name to an element 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 for the specified class name:

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

Step 3 - Add JavaScript:

get 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:Jak przełączać klasy

tutorial:Jak usunąć klasę

reference manual:Atrybut classList elementu DOM HTML

reference manual:Atrybut className elementu DOM HTML