Add Multiple Classes to HTML elements using JavaScript

In this article, we will learn how to add and remove multiple classes from a DOM element using Javascript.

In Javascript, we can use the classList property to add a class to an HTML element.

The element.classList property is a read-only property of an element that returns the CSS classes of an element. This property provides add() and remove() methods that allow us to add and remove classes from the HTML element.

Add Multiple Classes to an Element

So to add multiple classes to an HTML element, we have to select the DOM element and use the classList.add() method, and pass the class names as arguments.

For example, suppose we have a <div> element with some text and we want to add two classes to it.

<div id="my-div">
   <p>This is a random sentence</p>
</div>

Next, we will create some CSS classes to style the content of the <div> element.

.bg-color{
    background-color: yellow;
}

.text-color{
    color: red;
}

We have made two classes (bg-color and text-color) to add to the element.

Next, we will write the Javascript code to add those classes to the <div> element.

const mydiv = document.getElementById("my-div");

mydiv.classList.add("bg-color", "text-color");

Output:

add multiple elements to an element

Here, we have selected the <div> by its id using getElementById() method.

Next, we used the classList.add() method and passed the classes to add to the element.

Here in this example, we have just added two classes but we can add multiple classes using the classList.add() method in javascript.

Note:

  1. The add() method will ignore the class if it’s already added to the element.
  2. It will throw an error if an empty string is passed as an argument in the add() method.

Remove classes from an HTML element

Now, if we want to remove those classes then we can use the classList.remove() method.

We can remove one or multiple classes from an element by passing the names of the classes to be removed as an argument in the remove() method.

const mydiv = document.getElementById("my-div");

mydiv.classList.remove("bg-color", "text-color");

This will remove both classes from the element.

Conclusion:

To add one or more classes in an HTML element we have to use the classList.add() method and to remove classes we can use the classList.remove() method.


Scroll to Top