jQuery addClass() Method

The jQuery addClass() method can be used to add single or multiple classes to the selected element. It’s useful when you want to add or change the property of the selected element.

jQuery addClass() Method

Syntax of addClass() Method

The syntax of this method is given below:-

Add a class
$(selector).addClass(className)
Add more than one class
$(selector).addClass(className1 className2 className3…)
Use Function to add a class
$(selector).addClass(function(index, current_class))
Remove old class and add new class
$(selector).removeClass(oldclassName).addClass(newclassName)

Description of the Parameters

The description of the parameters are given below.

Parameter Name Description
selector Specify the selector to select the elements and add the class. You can use the tag name, class name, or id of the elements to select.
className It is the name of the class you want to add to the element. It can be single or multiple with spaces.
index An index returns the position of the selected element.
current_class It returns the current class name of the selected element.
oldclassName Specify the old class-name already present in the element to replace it with the new one.
newclassName Specify the new class name to replace the old class name.

jQuery addClass() Method Add a Class to the Element

If you want to add a single class to the selected element, you have to use the method as given in the example below. The example contains a button and a paragraph.

Example

Test it Live

Output

This is my paragraph

When you click the button given above, it adds a class to the selected element. The added class contains some CSS properties which automatically added when it adds a class.

Add More Than One Class Using the Method

You can also add more than one class to the selected element. Specify multiple class names with spaces. The below example add two classes to the element which also applies the CSS as well.

Example

Test it Live

Output

This is my paragraph

You have to click the button given above to add the multiple classes to the selected element. The two added classes apply padding, border and background color to the element.

How to Replace Class Using jQuery removeClass() and addClass() Method

The method is also useful when you want to replace the class for the selected element. You have to use the jQuery removeClass() method in addition with the jQuery addClass() method. The below example replaces the old class with the new class.

Example

Test it Live

Output

This is my paragraph

Click the button given above to replace the class with the new one. The newly added class add a different background color and text color to the element.

You may also like to read

I hope you like this tutorial on jQuery addClass() method. If you have any queries regarding the tutorial, please comment below.

References