HTML DOM className Property


The HTML DOM className property is used to assign a css class to an HTML element. The className property is used for setting or returning an element’s class name attribute value. If no class is associated with an HTML element, then an empty string is returned. We can change a class name contained with an element using this property −

Syntax

Following is the syntax for −

Setting the className property −

HTMLElementObject.className = class;

Here, the class value is used to specify the class name of an element. An element can have multiple classes associated with it separated by spaces.

Example

Let us see an example of the HTML DOM className property −

<!DOCTYPE html>
<html>
<head>
<style>
   .firstDiv {
      width: 300px;
      height: 100px;
      background-color:lightgreen;
   }
   .secondDiv{
      color: red;
      border:solid 1px blue;
      margin-bottom:9px;
   }
</style>
</head>
<body>
<p>Click the below button to display the class attribute value of the div </p>
<div id="myDIV" class="firstDiv secondDiv">
This is a sample div element.
</div>
<button onclick="getClassName()">GET CLASS</button>
<p id="Sample"></p>
<script>
   function getClassName() {
      var x = document.getElementById("myDIV").className;
      document.getElementById("Sample").innerHTML ="The classNames with the div element
         are "+x;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the GET CLASS button −

In the above example −

We have created a div with id “myDIV” and it contains some text in it −

<div id="myDIV" class="firstDiv secondDiv">
This is a sample div element.
</div>

We have then created a button GET CLASS that will execute the getClassName() method on click −

<button onclick="getClassName()">GET CLASS</button>

The getClassName() method will get the <div> element using the getElementById() method and gets all of its class name using the className property on the <div> element and assigns it to the variable x. The class names are then displayed in the paragraph with id “Sample” −

function getClassName() {
   var x = document.getElementById("myDIV").className;
   document.getElementById("Sample").innerHTML ="The classNames with the div element are "+x;
}

Updated on: 07-Aug-2019

68 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements