jQuery API 살펴보기 addClass 메서드

addClass() 메서드는 HTML 태그에 클래스 속성을 추가할때 사용하는 메서드이다.

1
$('selector').addClass('className');

두 개 이상의 클래스 속성을 추가할 때는 아래와 같이 사용해 주면 된다. 스페이스로 클래스명을 구분한다.

1
$('selector').addClass('myClass yourClass');

addClass() 메서드는 removeClass() 랑 자주 사용된다. 기존에 있던 클래스 속성을 지우고 새롭게 클래스 속성을 추가할때 사용된다.

1
$('selector').removeClass('myClass noClass').addClass('yourClass');

jQuery 1.4 이후부터는 addClass() 메서드에 함수를 매개변수로 입력할 수도 있다.

1
2
3
$('selector').addClass(function(index){
return 'class'+index;
})

예제

p 태그 선택자 마지막에 클래스 속성을 추가

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
<!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>

p 태그 선택자 마지막에 두 개의 클래스 속성을 추가

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
<!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>
<p>and</p>
<p>Goodbye</p>

<script>
$( "p:last" ).addClass( "selected highlight" );
</script>

</body>
</html>

addClass() 메서드에 함수를 매개변수로 입력한 예제

매개변수로 입력하는 함수는 index 매개변수를 갖는다. 선택자로 선택한 문서 객체에 차례대로 속성을 지정할 수 있다.

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
34
35
36
37
38
39
40
41
<!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>

<div>This div should be white</div>
<div class="red">This div will be green because it now has the "green" and "red" classes.
It would be red if the addClass function failed.</div>
<div>This div should be white</div>
<p>There are zero green divs</p>

<script>
$( "div" ).addClass(function( index, currentClass ) {
var addedClass;

if ( currentClass === "red" ) {
addedClass = "green";
$( "p" ).text( "There is one green div" );
}

return addedClass;
});
</script>

</body>
</html>
Share