The jQuery addClass() method is used to add one or more class names to a selected elements. To add more than one class name, separate them using spaces.
Syntax of jQuery addClass
1
| $(selector).addClass(classname,function(index,currentclass)) |
| Parameter | Description |
|---|---|
| classname | Required Parameter: names of the classes to be added to the selector |
| function(index,currentClass) | Optional Parameter: A function that returns one or more class names that are spaces-separated. The returned class names are added to the selector.
|
Example 1: Add a Single Class Name
I have a paragraph element to which I will apply Class red.
1
2
3
4
5
6
7
8
| <style>.red { color: Red;}</style><p id="myParagraph">My Paragraph</p><button id="myButton">Add Class</button> |
On the button Click I use jQuery addClass like this:
1
2
3
| $("#myButton").click(function (e) { $("#myParagraph").addClass("red");}); |
This will add the red Class to the paragraph and its color changes to Red.
Example 2: Add 3 Class Names
I can add more than one class to the selector using jQuery addClass. So here I add 3 Classes to the paragraph element. These classes are red, fontBold and borderSolid.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| <style>.red { color: Red;}.fontBold { font-weight: bold;}.borderSolid { border: solid 1px #4CAF50;}</style><p id="myParagraph">My Paragraph</p><button id="myButton">Add 3 Class</button> |
The jQuery code:
1
2
3
| $("#myButton").click(function (e) { $("#myParagraph").addClass("red fontBold borderSolid");}); |
In the jQuery addClass method each of the 3 class names are separated by space. So on the button click the myParagraph element will become – red in color, with font weight bold and a solid border.
Example 3: Using jQuery addClass Function Parameter
The return class name by the addClass() function parameter is applied to the selector. Let me show you how to use this function.
I have 3 paragraph element, 2 already have red class while the 3rd does not contain any class. Now I want to add borderSolid class to the paragraph whose index is not 0 and does not contain red class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| <style>.red { color: Red;}.borderSolid { border: solid 1px #4CAF50;}</style><p class="red">First Paragraph with class "Red"</p><p class="red">Second Paragraph with class "Red"</p><p>Third Paragraph without any class</p><button id="myButton">Add Class</button> |
The jQuery addClass code will be:
1
2
3
4
5
6
| $("#myButton").click(function (e) { $("p").addClass(function (index, currentClass) { if (index != 0 && currentClass == "red") return "borderSolid"; });}); |
I used the addClass function and did a check for index not 0 and currentClass not red.
I returned borderSolid at the end and this class is added to the 3rd paragraph element.

