How to use.className property in Javascript

This property is used to add a class name to the selected element.

Syntax:

// It is used to set the className property.
element.className = "newClass";

// It is used to return the className property.
element.className;

Property Value:

  • newClass: It specifies the element’s class name. For applying multiple classes, it needs to separate by space.

Return value: It is of string type which represents the class or list of classes of elements with space-separated.

Example: This example uses the .className property to add a class name.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>JavaScript to add class name</title>
    <style>
        .addCSS {
            color: green;
            font-size: 25px;
        }
    </style>
</head>
 
<body style="text-align:center;">
    <h1 style="color:green;">
        w3wiki
    </h1>
 
    <p id="p">
        A Computer Science portal for Geeks.
    </p>
 
    <button onclick="addClass()">
        AddClass
    </button>
 
    <!-- Script to add class name -->
    <script>
        function addClass() {
            let v = document.getElementById("p");
            v.className += "addCSS";
        }
    </script>
</body>
</html>


Output:

.className Property

JavaScript adding a class name to the element

The class name attribute can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name. Adding the class name by using JavaScript can be done in many ways. 

Below are the different approaches that could be used to add a class name to the element:

Table of Content

  • Using .className property
  • Using .add() method

Similar Reads

Approach 1: Using .className property

This property is used to add a class name to the selected element....

Approach 2: Using .add() method

...

Contact Us