Signup/Sign In
LAST UPDATED: AUGUST 4, 2021

How to add a class to a given element in JavaScript?

Answer: Using className Property

We can add a class to a given element in JavaScript using the className property. The className property is used to set or return the class name of the specified element.

Syntax

The syntax for adding class to an HTML element is given below:

HTMLElementObject.className = class

To add a class name to an HTML element, we have to first add the id to the HTML element for reference. Then we have to add the className property.

Example: Using className property

In the given example, we have added a class myClass using className property to the HTML div element.

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style>
		.myClass {
		  width: 300px;
		  height: 100px;
		  background-color: red;
		  text-align: center;
		  font-size: 25px;
		  color: white;
		  margin-bottom: 10px;
		}
	</style>
</head>
<body>
	<button onclick="myFunction()">Click Here</button>
	<div id="myID">Hello World!</div>
	<script>
		function myFunction() {
		  document.getElementById("myID").className = "myClass";
		}
	</script>
</body>
</html>

Output

Before clicking on the button

image1

After clicking on the button

image_2

Using classList property

This property returns the class names of an element as an DOMTokenList object. We can add, remove and toggle CSS classes on an element.

The classList property is read-only so we can use this property along with the add() and remove() methods.

Syntax

element.classList

Example: Using classList property

In this example, we have added a class myClass to the div element using the classList property along with the add() method.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<style type="text/css">
    .myClass {
          width: 300px;
          height: 100px;
          padding: 20px;
          background-color: red;
          color: white;
          font-size: 20px;
}
</style>
<body>
    <button onclick="myFunction()">Try it</button>
    <div id="myID">Hello World!</div>
    <script type="text/javascript">
        function myFunction() {
          var newClass = document.getElementById("myID");
          newClass.classList.add("myClass");
}
    </script>
</body>
</html>

Output

Before clicking on the button

image_3

After clicking on the button


image_4

Conclusion

In this lesson, we have learned to add a class to a given element in JavaScript. Here, we have discussed two methods first one is using className property, and the second method is using classList property. The classList property is a read-only property, so we have to use this property along with the add() method to add a new property.



About the author: