Escolar Documentos
Profissional Documentos
Cultura Documentos
className
Type: String
One or more space-separated classes to be added to the class attribute of each
matched element.
version added: 1.4.addClass( function )
function
This method is often used with .removeClass() to switch elements' classes from
one to another, like so:
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 two <li> elements, this example adds the class "item0" to the first <li> and "item-1" to the second.
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>addClass demo</title>
<style>
p {
margin: 8px;
font-size: 16px;
}
.selected {
color: blue;
}
.highlight {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p>
<p>and</p>
<p>Goodbye</p>
<script>
$( "p" ).last().addClass( "selected" );
</script>
</body>
</html>
19
20
21
22
23
24
25
26
27
28
29
30
31
Demo:
Example: Add the classes "selected" and "highlight" to the matched
elements.
1
2
3
4
5
6
7
8
9
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>addClass demo</title>
<style>
p {
margin: 8px;
font-size: 16px;
}
.selected {
color: red;
}
.highlight {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p>
10
11
12
13
14
15
16
17
18
19
20
21
22
<p>and</p>
<p>Goodbye</p>
<script>
$( "p:last" ).addClass( "selected highlight" );
</script>
</body>
</html>
23
24
25
26
27
28
29
30
31
Demo:
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>addClass demo</title>
<style>
div {
background: white;
}
.red {
background: red;
}
.red.green {
background: green;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Demo: