Table of contents
1.
Introduction
2.
Using className Property
2.1.
Syntax
3.
Example 1: Adding a Single Class
4.
Example 2: Adding Multiple Classes
4.1.
Key Consideration
5.
Using .add() Method
5.1.
Syntax
5.2.
Example 1: Adding a Single Class
5.3.
Example 2: Adding Multiple Classes
5.4.
Key Features of .add()
6.
Toggle Method  
6.1.
How the Toggle Method Works  
6.2.
Example: Toggling a Class  
7.
Differences Between className and .add()
8.
Frequently Asked Questions
8.1.
Can I use both className and .add() together?
8.2.
What happens if I add a class that already exists using .add()?
8.3.
Which method should I use for dynamic web applications?
9.
Conclusion
Last Updated: Jan 12, 2025
Easy

JavaScript Add Class

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JavaScript addClass is a useful method that allows developers to add one or more CSS classes to an HTML element. This can be helpful when you want to change the style or appearance of an element dynamically. By adding a class, you can modify the element's look or behavior based on user interactions, without directly altering its inline styles.

JavaScript Add Class

This article will discuss the two main methods for adding classes in JavaScript: the className property and the .add() method. 

Using className Property

The className property allows you to directly assign a string of class names to an HTML element. This method replaces all existing classes on the element with the specified classes.

Syntax

element.className = "class1 class2";

Example 1: Adding a Single Class

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Using className</title>
    <style>
        .highlight {
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <p id="myText">Hello, Coding Ninjas!</p>

    <script>
        const element = document.getElementById("myText");
        element.className = "highlight";
    </script>
</body>
</html>


Output:

Output

The text "Hello, Coding Ninjas!" will appear in red and bold.

Example 2: Adding Multiple Classes

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Adding Multiple Classes</title>
    <style>
        .highlight {
            color: red;
        }
        .italic {
            font-style: italic;
        }
    </style>
</head>
<body>
    <p id="myText">Hello, Coding Ninjas!</p>
    <script>
        const element = document.getElementById("myText");
        element.className = "highlight italic";
    </script>
</body>
</html>


Output:

Output


The text "Hello, Coding Ninjas!" will be red and italicized.

Key Consideration

Using className overwrites any existing classes on the element. If the element already has classes, you'll need to manually include them in the new assignment.

Using .add() Method

The .add() method is a part of the classList API. It allows you to add one or more classes to an element without affecting existing classes.

Syntax

element.classList.add("class1", "class2");

Example 1: Adding a Single Class

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Using .add()</title>
    <style>
        .highlight {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <p id="myText">Hello, Coding Ninjas!</p>


    <script>
        const element = document.getElementById("myText");
        element.classList.add("highlight");
    </script>
</body>
</html>


Output:

Output

Example 2: Adding Multiple Classes

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Adding Multiple Classes</title>
    <style>
        .highlight {
            color: blue;
        }
        .underline {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <p id="myText">Hello, Coding Ninjas!</p>
    <script>
        const element = document.getElementById("myText");
        element.classList.add("highlight", "underline");
    </script>
</body>
</html>


Output:

Output


The text "Hello, Coding Ninjas!" will be blue and underlined.

Key Features of .add()

  • It preserves existing classes.
     
  • It allows you to add multiple classes at once.

Toggle Method  

The `toggle` method in JavaScript is a handy way to add or remove a class from an HTML element. It works like a switch: if the class is already present, it removes it; if it’s not present, it adds it. This is particularly useful for creating interactive features like dark mode toggles, collapsible menus, or highlighting elements.  

How the Toggle Method Works  

The `toggle` method is part of the `classList` property, which is available on all HTML elements. Here’s the basic syntax:  

element.classList.toggle('className');
  • `element`: The HTML element you want to modify.  
     
  • `className`: The name of the class you want to toggle.  

Example: Toggling a Class  

Let’s say you have a button that changes the background color of a paragraph when clicked. Let’s see how you can achieve this using the `toggle` method:  

1. HTML Structure:  

<p id="myParagraph">This is a sample paragraph.</p>
<button id="toggleButton">Toggle Background</button>


2. CSS Styling:  

.highlight {
  background-color: yellow;
}


3. JavaScript Code:  

// Step 1: Select the elements

const paragraph = document.getElementById('myParagraph');
const button = document.getElementById('toggleButton');


// Step 2: Add an event listener to the button

button.addEventListener('click', () => {
  // Step 3: Toggle the 'highlight' class on the paragraph
  paragraph.classList.toggle('highlight');
});


In this code:   

1. HTML: We have a paragraph (`<p>`) & a button (`<button>`). The paragraph will change its background color when the button is clicked.  
 

2. CSS: The `.highlight` class defines the background color as yellow.  
 

3. JavaScript:  

   - We select the paragraph & button using `getElementById`.  
 

   - We add a `click` event listener to the button.  
 

   - When the button is clicked, the `toggle` method is called on the paragraph’s `classList`. This adds the `highlight` class if it’s not present & removes it if it is.  


Practical Use Cases  

  • Dark Mode Toggle: You can use the `toggle` method to switch between light & dark themes by toggling a `dark-mode` class on the `<body>` element.  
     
  • Collapsible Menus: Toggle a `hidden` class to show or hide dropdown menus.  Interactive Forms: Highlight input fields when they are focused or contain errors.  

Differences Between className and .add()

FeatureclassName.add()
PurposeReplaces all existing classes.Adds new classes while keeping existing ones.
SyntaxAssigns a string of class names.Adds classes using a method.
Error HandlingMay accidentally overwrite classes.Avoids overwriting existing classes.
Use CaseWhen replacing all classes is needed.When adding new classes without removing others.

Frequently Asked Questions

Can I use both className and .add() together?

Yes, but it's not recommended as className overwrites existing classes, which can conflict with .add() operations.

What happens if I add a class that already exists using .add()?

The .add() method checks for duplicates, so adding an existing class has no effect.

Which method should I use for dynamic web applications?

The .add() method is more versatile and should be your default choice, especially when you want to preserve existing classes.

Conclusion

In this article, we discussed how to add classes to HTML elements using JavaScript. The className property allows for direct assignment but overwrites existing classes, making it suitable for resetting class names. On the other hand, the .add() method from classList is more flexible, enabling the addition of new classes without affecting existing ones.

You can also check out our other blogs on Code360.

Live masterclass