jQuery API filter 메서드

선택된 요소 집합을 필터? 원하는대로 필터링 할 수 있다는 것 같다.

DOM 요소 집합을 나타내는 jQuery 객체가 주어지면 .filter () 메서드는 일치하는 요소의 하위 집합에서 새 jQuery 객체를 생성합니다. 우리가 일상생활에서 생각 하는 필터? 의 기능이 프로그래밍과 똑같은 것 같다. 필터링 한다는게 기존에 있던 거를 새로운 것으로 바꾼다? 라는 의미가 있는데 프로그래밍 언어에서도 똑같다. 기존에 jQuery 객체를 filter() 메서드를 통해서 새로운 jQuery 객체를 생성하는 것이다.

간단하게 먼저 살펴보자

1
2
3
4
5
6
7
8
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>

아래의 스크립트를 적용

1
$( "li" ).filter( ":even" ).css( "background-color", "red" );

결과는 :even 이라는 짝수 번째에 li 태그에 빨간색으로 배경색이 칠해진다. list item1, list item 3, list item 5 가 빨간색으로 칠해진다. 왜 짝수번째 라면서 1,3,5 냐고 생각할 수도 있는데 :even이나 :odd 는 index가 0을 기준으로 시작하기 때문이다!

Filter Function 사용

이 메서드의 인자로 function을 사용하면 선택자가 아닌 함수에 대해 요소를 필터링 할 수 있습니다. 각 요소에 대해 함수가 true (또는 “truthy”값)를 반환하면 요소가 필터링 된 집합에 포함됩니다. 그렇지 않으면 제외됩니다.

1
2
3
4
5
6
7
8
9
<ul>
<li><strong>list</strong> item 1 - one strong tag</li>
<li><strong>list</strong> item <strong>2</strong> -
two <span>strong tags</span></li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>

list item을 선택한 다음 그것들의 내용을 기준으로 필터링 할 수 있다.

1
2
3
4
5
$( "li" )
.filter(function( index ) {
return $( "strong", this ).length === 1;
})
.css( "background-color", "red" );

이 코드는 정확히 하나의 strong 태그를 포함하므로 첫 번째 목록 항목 만 변경합니다. 위에서 사용된 this 키워드는 리스트(li)를 의미한다. 즉 모든 li들이 this에 한 번씩 해당하게 된다. 인자로 넘겨진 index는 각 li들의 index를 뜻한다. 필터 함수 내에서 이것은 차례대로 각 DOM 요소를 참조합니다. 함수에 전달 된 매개 변수는 jQuery 객체와 일치하는 집합 내의 DOM 요소 색인을 알려줍니다.

또한 함수를 통해 전달 된 인덱스를 활용할 수도 있다.이 인덱스는 일치하는 요소 집합내의 인덱스를 말한다. 인덱스는 0부터 시작

1
2
3
4
5
$( "li" )
.filter(function( index ) {
return index % 3 === 2;
})
.css( "background-color", "red" );

3으로 나눴을 때 나머지가 2인 li들만 배경색이 빨간색으로 변경된다.

예제

모든 div 들의 배경색을 바꾸고 클래스가 middle인 div의 테두리를 빨간색으로 바꿔줍니다.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>filter demo</title>
<style>
div {
width: 60px;
height: 60px;
margin: 5px;
float: left;
border: 2px white solid;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<div></div>
<div class="middle"></div>
<div class="middle"></div>
<div class="middle"></div>
<div class="middle"></div>
<div></div>

<script>
$( "div" )
.css( "background", "#c8ebcc" )
.filter( ".middle" )
.css( "border-color", "red" );
</script>

</body>
</html>

예제

div들의 배경색을 바꾼다. 그리고 index가 1인 경우와 id값이 fourth 인 경우에는 추가적으로 border 속성을 추가한다. 위에서 살펴본 인덱스를 활용한 filter

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>filter demo</title>
<style>
div {
width: 60px;
height: 60px;
margin: 5px;
float: left;
border: 3px white solid;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
<div id="fourth"></div>
<div id="fifth"></div>
<div id="sixth"></div>

<script>
$( "div" )
.css( "background", "#b4b0da" )
.filter(function( index ) {
return index === 1 || $( this ).attr( "id" ) === "fourth";
})
.css( "border", "3px double red" );
</script>

</body>
</html>
Share