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

next() 메서드는 HTML 내에서 지정한 요소의 다음 요소를 반환하는 메서드이다.

DOM 요소 집합을 나타내는 jQuery 객체가 주어지면 .next () 메서드를 사용하면 DOM 트리에서 이러한 요소의 바로 다음 형제를 검색하고 일치하는 요소에서 새 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>next demo</title>
<style>
span {
color: blue;
font-weight: bold;
}
button {
width: 100px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<div><button disabled="disabled">First</button> - <span></span></div>
<div><button>Second</button> - <span></span></div>
<div><button disabled="disabled">Third</button> - <span></span></div>

<script>
$( "button[disabled]" ).next().text( "this button is disabled" );
</script>

</body>
</html>

위의 예제를 실행하면 비 활성화된 버튼 요소를 찾아서 그 요소의 다음 노드에 text를 작성한다.

위의 소스는 비 활성화된 버튼이 2개가 있는데 그 2개의 요소 다음 형제 요소는 span 태그이다.

그러니 결과를 보면 span 태그 안에 this button is disabled 라는 텍스트가 들어가있는 것을 확인할 수 있다.

다음 예제를 살펴보자

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>next demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Hello</p>
<p class="selected">Hello Again</p>
<div><span>And Again</span></div>

<script>
$( "p" ).next( ".selected" ).css( "background", "yellow" );
</script>

</body>
</html>

예제의 스크립트 부분을 보면 p 태그에 대해서 next() 메서드를 사용한 후에 그 다음 형제 요소 중에 selected 라는 클래스 속성을 가지고 있는 요소만 css를 변경한다.

Share