jQuery API find 메서드

find() 메서드

선택자, jQuery 객체 요소를 찾아서 일치하는 요소의 하위 요소를 찾는 메서드

즉 인자로 넘어간 선택자의 하위 요소를 찾아준다.

find()와 children() 의 차이점은 find()는 DOM 레벨 트리에서 요소의 모든 자식 요소를 검색하고 children()은 DOM 레벨 트리에서 바로 아래 단계 자식 요소만을 추출하는 점에서 차이가 있다. 예제를 보자

예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>find demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>

<script>
$( "p" ).find( "span" ).css( "color", "red" );
//same as $("p span")
</script>

</body>
</html>

p 태그 밑에 자식인 span 태그 모두 css를 적용 인자를 선택자 태그 span으로 넣었다. 위의 예제는 $(“p span”) 으로 해도 된다.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>find demo</title>
<style>
span {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>
<div>Did you <span>eat</span> yet?</div>

<script>
var spans = $( "span" );
$( "p" ).find( spans ).css( "color", "red" );
</script>

</body>
</html>

예제의 결과를 보면 맨 아래 div 태그 밑의 span 태그는 변경되지 않았다. p태그의 모든 하위 자식들만 코드를 수행하고 가장 아래의 span 태그는 div 태그의 하위 태그라 적용되지 않았다. 그리고 이 두번째 예제는 인자를 jQuery 객체를 넣었다.

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
49
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>find demo</title>
<style>
p {
font-size: 20px;
width: 200px;
color: blue;
font-weight: bold;
margin: 0 10px;
}
.hilite {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>
When the day is short
find that which matters to you
or stop believing
</p>

<script>
var newText = $( "p" ).text().split( " " ).join( "</span> <span>" );
newText = "<span>" + newText + "</span>";

$( "p" )
.html( newText )
.find( "span" )
.hover(function() {
$( this ).addClass( "hilite" );
}, function() {
$( this ).removeClass( "hilite" );
})
.end()
.find( ":contains('t')" )
.css({
"font-style": "italic",
"font-weight": "bolder"
});
</script>

</body>
</html>

설명은 즐거움을 찾자 Find Fun!! 님의 설명으로 대신한다..정말 잘하시는것 같다. 사실 여기를 좀 많이 참고해서 정리하고있다.

Share