How to add a class to an element using JavaScript?

The class attribute can be used in CSS to do some tasks for the elements with the corresponding class name. In this article, we are discussing how to add a class to an element using JavaScript. In JavaScript, there are some approaches to add a class to an element. We can use the .className property or the .add() method to add a class name to the particular element.

Now, let's discuss the approaches to add a class to an element.

Using .className property

The .className property sets the class name of an element. This property can be used to return the value of the class attribute of an element. We can use this property to add a class to an HTML element without replacing its existing class.

To add multiple classes, we have to separate their name with space such as"class1 class2".

If a class is already declared for an element, and we need to add a new class name to the same element then it should be declared by inserting a space before writing the new class name otherwise, it will overwrite the existing class name. It can be written as follows:

In the above code, we have inserted a space before newClass.

Syntax

The commonly used syntax of this property to set or to return the class name is given below.

To set the class name

To return the class name

The example of using the .className property is given as follows.

Example - Adding the class name

In this example, we are using the .className property for adding the "para" class to the paragraph element having id "p1". We are applying the CSS to the corresponding paragraph using the class name "para".

We have to click the given HTML button "Add Class" to see the effect.

Test it Now

Output

How to add a class to an element using JavaScript

After clicking the given button, the output will be -

How to add a class to an element using JavaScript

In the next example, we are getting the name of the class by using the .className property.

Example - Getting the class name

In this example, we are using the .className property to get the class names of the paragraph element having id = "p1".

We have to click the given HTML button "Get Class name" to see the effect.

Test it Now

Output

How to add a class to an element using JavaScript

After clicking the given button, the output will be -

How to add a class to an element using JavaScript

Using add() method

Now, let's see the second approach of adding the class name using JavaScript. We can use the add() method to add a class name to the particular element.

Syntax

Example

In this example, we are using the add() method to add a class name to the paragraph element having id = "p1". We have to click the given HTML button "Add Class" to see the effect.

Test it Now

Output

How to add a class to an element using JavaScript

After clicking the given button, the output will be -

How to add a class to an element using JavaScript




Latest Courses