Javascript DOM HTML Element className Property set

Introduction

Set the class for a <div> element with id="myDIV":

document.getElementById("myDIV").className = "mystyle";

Click the button to set a class for div.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {//  ww  w  . jav  a2s. c  om
  width: 300px;
  height: 100px;
  background-color: coral;
  text-align: center;
  font-size: 25px;
  color: white;
  margin-bottom: 10px;
}
</style>
</head>
<body>
<div id="myDIV">
I am a DIV element
</div>

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {
  document.getElementById("myDIV").className = "mystyle";
}
</script>

</body>
</html>

The className property sets or gets the class name of an element.

The className property reflects the value of an element's class attribute.

To apply multiple classes, separate them with spaces, like "test demo"

The className property returns a String representing the class, or a space-separated list of classes, for an element.




PreviousNext

Related