How can I add a class to an existing element in JavaScript?

How can I add a class to an existing element in JavaScript?

I have a div element with a class already assigned:

<div class="someclass">
    <img ... id="image1" name="image1" />
</div>

I want to create a JavaScript function that adds another class to the div without replacing the current class.

How can I accomplish this?

hey Prynka,

If you are targeting modern browsers, use element.classList.add to add a class:

element.classList.add("my-class");

To remove a class, use element.classList.remove:

element.classList.remove("my-class");

If you need to support Internet Explorer 9 or lower, add a space followed by the new class name to the className property of the element. First, assign an id to the element to easily reference it:

<div id="div1" class="someclass">
    <img ... id="image1" name="image1" />
</div>

Then, use the following JavaScript:

var d = document.getElementById("div1");
d.className += " otherclass";

Note the space before “otherclass”. It’s important to include the space to ensure it does not interfere with existing classes in the class list.

Hello Priyanka,

I hope you are doing well here is the to the question:-

The simplest way to add a class without using any framework is to utilize the element.classList.add method:

var element = document.getElementById("div1");
element.classList.add("otherclass");

To remove a class from an element, use:

element.classList.remove("otherclass");

I prefer this method because it avoids the need to manually handle empty spaces and duplicate entries, which is necessary when using the element.className approach. Although there are some browser limitations, you can address them with a polyfill.

Hello Priyanka,

Two Different Ways to Add a Class Using JavaScript

JavaScript offers two methods to add classes to HTML elements:

  1. Using element.classList.add() Method
  2. Using className Property

Both methods allow you to add single or multiple classes at once.

1. Using element.classList.add() Method

var element = document.querySelector('.box');

// Adding a single class
element.classList.add('color');

// Adding multiple classes
element.classList.add('border', 'shadow');
.box {
    width: 200px;
    height: 100px;
}
.color {
    background: skyblue;
}
.border {
    border: 2px solid black;
}
.shadow {
    box-shadow: 5px 5px 5px gray;
}
<div class="box">My Box</div>

2. Using className Property

Note: Always use the += operator and add a space before the class name when adding classes with the className property.

var element = document.querySelector('.box');

// Adding a single class
element.className += ' color';

// Adding multiple classes (space-separated)
element.className += ' border shadow';
.box {
    width: 200px;
    height: 100px;
}
.color {
    background: skyblue;
}
.border {
    border: 2px solid black;
}
.shadow {
    box-shadow: 5px 5px 5px gray;
}
<div class="box">My Box</div>