How to Add a Class in JavaScript

JavaScript provides several methods to manipulate classes on HTML elements. In this article, we’ll explore how to add a class to an HTML element using JavaScript.

What is a Class in HTML?

In HTML, a class is an attribute used to define a set of CSS styles that can be applied to multiple elements. Classes are defined in the <style> tag or in external CSS files and are applied to HTML elements using the class attribute.

How to Add a Class in JavaScript

There are several ways to add a class to an HTML element using JavaScript. The most common methods are:

  1. Using the classList.add() method
  2. Using the className property
  3. Using the setAttribute() method

1. Using the classList.add() Method

The classList property returns a collection of the class names of an element. The add() method adds a new class to the element.

Syntax

element.classList.add(className);

Example

<!DOCTYPE html>
<html>
<head>
    <style>
        .highlight {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <p id="myParagraph">Hello World!</p>
    <button onclick="addHighlightClass()">Highlight</button>

    <script>
        function addHighlightClass() {
            const paragraph = document.getElementById("myParagraph");
            paragraph.classList.add("highlight");
        }
    </script>
</body>
</html>

In this example, when the button is clicked, the addHighlightClass() function is called. This function gets the paragraph element by its ID and adds the highlight class to it. The highlight class changes the background color of the paragraph to yellow.

2. Using the className Property

The className property sets or returns the class attribute of an element. You can use this property to add a class to an element.

Syntax

element.className += " " + className;

Example

<!DOCTYPE html>
<html>
<head>
    <style>
        .highlight {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <p id="myParagraph">Hello World!</p>
    <button onclick="addHighlightClass()">Highlight</button>

    <script>
        function addHighlightClass() {
            const paragraph = document.getElementById("myParagraph");
            paragraph.className += " highlight";
        }
    </script>
</body>
</html>

This example works similarly to the previous one, but instead of using classList.add(), it uses the className property to add the highlight class.

3. Using the setAttribute() Method

The setAttribute() method sets the value of an attribute for the specified element. You can use this method to add a class to an element.

Syntax

element.setAttribute("class", className);

Example

<!DOCTYPE html>
<html>
<head>
    <style>
        .highlight {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <p id="myParagraph">Hello World!</p>
    <button onclick="addHighlightClass()">Highlight</button>

    <script>
        function addHighlightClass() {
            const paragraph = document.getElementById("myParagraph");
            paragraph.setAttribute("class", "highlight");
        }
    </script>
</body>
</html>

This example also adds the highlight class to the paragraph element, but it uses the setAttribute() method.

Real-World Applications

Adding classes dynamically using JavaScript is a common practice in web development. Here are some real-world applications:

  • Dynamic Styling: You can change the appearance of elements based on user interactions or other conditions.
  • Show/Hide Elements: You can add or remove classes to show or hide elements.
  • Form Validation: You can add classes to highlight valid or invalid form fields.
  • Interactive UI: You can add classes to create interactive user interfaces, such as hover effects, active states, etc.

Frequently Asked Questions

Q1. Can I add multiple classes at once?

Yes, you can add multiple classes at once using the classList.add() method by passing multiple class names as arguments.

Example

paragraph.classList.add("highlight", "bold");

Q2. How can I remove a class?

You can remove a class using the classList.remove() method.

Example

paragraph.classList.remove("highlight");

Q3. How can I toggle a class?

You can toggle a class using the classList.toggle() method. If the class exists, it removes it; if it doesn’t exist, it adds it.

Example

paragraph.classList.toggle("highlight");

Q4. How can I check if a class exists?

You can check if a class exists using the classList.contains() method.

Example

if (paragraph.classList.contains("highlight")) {
    console.log("The class exists.");
}

Q5. Can I add a class to multiple elements at once?

Yes, you can add a class to multiple elements at once by selecting all the elements and looping through them to add the class.

Example

const paragraphs = document.querySelectorAll("p");
paragraphs.forEach(paragraph => {
    paragraph.classList.add("highlight");
});

This code adds the highlight class to all paragraph elements on the page.

Conclusion

Adding classes dynamically using JavaScript is a powerful way to create interactive and responsive web applications. Whether you’re adding a single class or multiple classes, JavaScript provides several methods to make this process easy and efficient. Experiment with these methods to create dynamic and engaging user experiences.

Index
Scroll to Top