Open In App

How to Add a Class to DOM Element in JavaScript?

Last Updated : 26 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Adding a class to a DOM (Document Object Model) element in JavaScript is a fundamental task that enables developers to dynamically manipulate the appearance and behavior of web pages. Classes in HTML provide a powerful way to apply CSS styles or JavaScript functionality to multiple elements at once.

By using JavaScript, you can easily add, remove, or toggle classes on elements, making your web applications more interactive and responsive to user actions.

These are the following approaches:

Using classList Property

In this approach, we are using classList property to add the class into the DOM element. It returns the class name as a DOMTokenList object. It has a method called “add” which is used to add class name to elements. we will access the div using the getElementById and we will use the add property of classList to add a class.

Syntax:

element.classList.add("className")

Example: This example shows the implementation of the above-explained approach.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
        .geek {
            background-color: green;
            font-size: 50px;
        }
    </style>
</head>

<body>

    <button onclick="myClass()">Try it</button>

    <div id="gfg">Geeks for Geeks</div>

    <script>
        function myClass() {
            let elem = document.getElementById("gfg");

            // Adding class to div element 
            elem.classList.add("geek");
        } 
    </script>

</body>

</html>

Output:

addClass

Using className Property

In this approach, we are using the clasName property. This property returns the className of the element. If the element has already a class then it will simply add another one to it or else it will append our new class to it.

Syntax:

HTMLElementObject.className

Example: This example shows the implementation of the above-explained approach.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
        .geekClass {
            background-color: green;
            text-align: center;
            font-size: 50px;
        }
    </style>
</head>

<body>

    <div id="gfg">
        Geeks For Geeks
    </div>

    <button onclick="myClassName()">Add Class</button>

    <script>
        function myClassName() {
            let element = document.getElementById("gfg");

            // Adding the class geekClass to element 
            // with id gfg space is given in className 
            // (" geekClass") as if there is already 
            // a class attached to an element than our 
            // new class won't overwrite and will append 
            // one more class to the element 
            element.className += " geekClass";
        } 
    </script>

</body>

</html>

Output:

addClass

Output



Next Article

Similar Reads