How to add a class in an element by JavaScript?

In your web pages, you may add or remove CSS classes from the DOM elements on the fly. No jQuery or some other library is required but this can be done easily by raw JavaScript.

In JavaScript, the elements.classList is a property that can be used for adding/removing classes to the specified elements.

For example:

divtst.classList.add(“anotherclass”);

Where:

divtst specifies the element where you want to add a new class name.

This is followed by the classList property.

Then add method is used and the desired class name is provided in the parenthesis.

The examples below show how to specify element and add CSS class in different elements.

An example of adding a CSS class in a div element

In the first example of explaining how to add a class, I am using a div element. The div tag simply displays plain text without any style as the example page loads.

As you click on the button “Add class”, the tstClass that contains a few CSS properties will be applied to that div element. See the example and output by clicking the link or image below:

JavaScript add class

See online demo and code

The JS for this example:

The CSS class:

The markup:

An example of adding a class in HTML table

By using JavaScript classList property’s Add method, you may add the CSS class to different elements. In the following example, a raw table without any CSS is created as the web page loads.

Again, as you click the button, the CSS style class will be added to the table by using JavaScript:

See online demo and code

The JavaScript used for adding class to the table element:

Following is the CSS class:

See the complete code including markup in the example page.

Does classList add method remove existing class?

In order to test if classList removes existing class before adding a new class, I have created a div element with the basic style. The initial class applied to the div tag is “cls1” that set the following properties to the div element:

Text size, color

As you click the button, the “cls2” class is added to the div element by classList add method. This class does not contain size and color properties. Rather it contains a few other properties like padding, border etc.

See if it removes the text size and color applied by cls1 class or not:

JavaScript add css

See online demo and code

The code:

You can see, the properties of cls1 class remain while properties of the cls2 class are also added. So it does not override or remove the existing class(es).