.addClass( className ) Returns: jQuery
Description: Adds the specified class(es) to each of the set of matched elements.
-
version added: 1.0.addClass( className )
-
classNameType: StringOne or more space-separated classes to be added to the class attribute of each matched element.
-
-
version added: 1.4.addClass( function(index, currentClass) )
-
function(index, currentClass)Type: Function()A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function,
this
refers to the current element in the set.
-
It's important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements.
More than one class may be added at a time, separated by a space, to the set of matched elements, like so:
1
|
|
This method is often used with .removeClass()
to switch elements' classes from one to another, like so:
1
|
|
Here, the myClass
and noClass
classes are removed from all paragraphs, while yourClass
is added.
As of jQuery 1.4, the .addClass()
method's argument can receive a function.
1
2
3
|
|
Given an unordered list with five <li>
elements, this example adds the class "item-4" to the last <li>
.
Examples:
Example: Add the class "selected" to the matched elements.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
|
Example: Add the classes "selected" and "highlight" to the matched elements.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
|
Example: Pass in a function to .addClass()
to add the "green" class to a div that already has a "red" class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
|