jQuery API 살펴보기 each() 메서드

.each() 메서드는 DOM 문서 객체의 선택된 요소를 지정한 수 만큼 반복시켜주는 메서드이다.

선택된 HTML의 요소를 반복을 돌면서 jQuery 객체를 DOM에 생성한다.

음..즉 그냥 자바스크립트에서 for-each 같은 반복문인데 이 .each() 메서드는 HTML DOM 구조를 가지고 반복문을 돌린다.

이때 callback 안에서 this라는 키워드를 사용할 수 있는데 이때 this는 호출된 선택자의 this값이다.

또한 이 .each() 메서드는 jQuery.each() 메서드와는 또 다르다. 전자는 DOM 구조에 대한 반복을 실행할 수 있고 후자는 배열이나 XML 객체 등을 반복하는데 사용된다.

예제

간단한 예제를 보면서 확인해보자. 아래와 같은 html이 있다고 했을 때

1
2
3
4
<ul>
<li>foo</li>
<li>bar</li>
</ul>

li라는 선택자를 넣고 each() 메서드를 실행한다. 여기서 index는 0부터 시작한다. li가 있는 개수 만큼 반복된다.

또한 여기서 this는 반복을 수행하면서 현재 반복되고 있는 어떤 DOM 구조에 추가적인 작업을 할 수 가 있다.

1
2
3
$( "li" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});

위의 결과는 아래와 같이 나온다. 그리고 반복을 멈추고 싶을 때는 return false를 추가하면 된다.

1
2
0: foo
1: bar

클릭에 따라서 div안에 text 색깔이 바뀌는 예제

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>each demo</title>
<style>
div {
color: red;
text-align: center;
cursor: pointer;
font-weight: bolder;
width: 300px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<div>Click here</div>
<div>to iterate through</div>
<div>these divs.</div>

<script>
$( document.body ).click(function() {
$( "div" ).each(function( i ) {
if ( this.style.color !== "blue" ) {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
});
</script>

</body>
</html>

일반 DOM 요소 대신 jQuery 객체에 접근하기 위해서는 $(this)를 사용해서 접근한다.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>each demo</title>
<style>
ul {
font-size: 18px;
margin: 0;
}
span {
color: blue;
text-decoration: underline;
cursor: pointer;
}
.example {
font-style: italic;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

To do list: <span>(click here to change)</span>
<ul>
<li>Eat</li>
<li>Sleep</li>
<li>Be merry</li>
</ul>

<script>
$( "span" ).click(function() {
$( "li" ).each(function() {
$( this ).toggleClass( "example" );
});
});
</script>

</body>
</html>

위에서 얘기했던 반복을 멈추고싶을 때 return false 를 쓰는 예제

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
42
43
44
45
46
47
48
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>each demo</title>
<style>
div {
width: 40px;
height: 40px;
margin: 5px;
float: left;
border: 2px blue solid;
text-align: center;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<button>Change colors</button>
<span></span>
<div></div>
<div></div>
<div></div>
<div></div>
<div id="stop">Stop here</div>
<div></div>
<div></div>
<div></div>

<script>
$( "button" ).click(function() {
$( "div" ).each(function( index, element ) {
// element == this
$( element ).css( "backgroundColor", "yellow" );
if ( $( this ).is( "#stop" ) ) {
$( "span" ).text( "Stopped at div index #" + index );
return false;
}
});
});
</script>

</body>
</html>
Share