.closest (selector)
.closest (selector)
설명 : 집합의 각 요소에 대해 요소 자체를 테스트하고 DOM 트리에서 조상을 통해 위로 이동하여 선택기와 일치하는 첫 번째 요소를 가져옵니다.
DOM 요소 집합을 나타내는 jQuery 객체가 주어지면이 .closest()메소드는 DOM 트리에서 이러한 요소와 조상을 검색하고 일치하는 요소에서 새 jQuery 객체를 생성합니다. .parents()및 .closest()방법은 모두 DOM 트리를 횡단 점에서 유사하다. 이 둘의 차이는 미묘하지만 중요합니다.
<ul id="one" class="level-1">
<li class="item-i">I</li>
<li id="ii" class="item-ii">II
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
<ul>항목 A에서 시작 하는 요소를 검색한다고 가정 해 보겠습니다 .
$( "li.item-a" )
.closest( "ul" )
.css( "background-color", "red" );
레벨 2의 색상이 변경 <ul>됩니다. DOM 트리 위로 올라갈 때 처음으로 발생하기 때문입니다.
<li>대신 에 요소를 검색한다고 가정 해보십시오 .
$( "li.item-a" )
.closest( "li" )
.css( "background-color", "red" );
이렇게하면 목록 항목 A의 색상이 변경 .closest()됩니다 . 메서드는 DOM 트리를 진행하기 전에 요소 자체에서 검색 을 시작하고 항목 A가 선택기와 일치하면 중지합니다.
가장 가까운 요소를 검색 할 컨텍스트로 DOM 요소를 전달할 수 있습니다.
var listItemII = document.getElementById( "ii" );
$( "li.item-a" )
.closest( "ul", listItemII )
.css( "background-color", "red" );
$( "li.item-a" )
.closest( "#one", listItemII )
.css( "background-color", "green" );
목록 항목 A <ul>의 첫 번째 상위 <ul>항목이고 목록 항목 II의 하위 항목 이기 때문에 레벨 2의 색상이 변경됩니다 . <ul>그러나 목록 항목 II의 하위 항목이 아니기 때문에 레벨 -1의 색상은 변경 되지 않습니다.
게시판 목록
개발자팁
질문은 QA에서 해주시기 바랍니다.
| 번호 | 분류 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|---|
| 4736 | jQuery | 8년 전 | 1562 | ||
| 4735 | jQuery | 8년 전 | 1751 | ||
| 4734 | jQuery | 8년 전 | 1741 | ||
| 4733 | jQuery | 8년 전 | 2036 | ||
| 4732 | jQuery | 8년 전 | 1959 | ||
| 4731 | jQuery | 8년 전 | 1460 | ||
| 4730 | jQuery | 8년 전 | 1919 | ||
| 4729 | PHP |
|
8년 전 | 6906 | |
| 4728 | jQuery | 8년 전 | 2563 | ||
| 4727 | jQuery | 8년 전 | 1612 | ||
| 4726 | jQuery | 8년 전 | 1692 | ||
| 4725 | jQuery | 8년 전 | 1835 | ||
| 4724 | jQuery | 8년 전 | 1312 | ||
| 4723 | jQuery | 8년 전 | 1865 | ||
| 4722 | jQuery | 8년 전 | 1630 | ||
| 4721 | jQuery | 8년 전 | 1919 | ||
| 4720 | jQuery | 8년 전 | 1979 | ||
| 4719 | jQuery | 8년 전 | 1603 | ||
| 4718 | jQuery | 8년 전 | 1609 | ||
| 4717 | jQuery | 8년 전 | 1560 | ||
| 4716 | jQuery | 8년 전 | 1239 | ||
| 4715 | jQuery | 8년 전 | 1396 | ||
| 4714 | jQuery | 8년 전 | 1419 | ||
| 4713 | jQuery | 8년 전 | 1338 | ||
| 4712 | jQuery | 8년 전 | 2228 | ||
| 4711 | jQuery | 8년 전 | 1716 | ||
| 4710 | PHP |
|
8년 전 | 3748 | |
| 4709 | jQuery | 8년 전 | 1630 | ||
| 4708 | jQuery | 8년 전 | 1910 | ||
| 4707 | jQuery | 8년 전 | 1768 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기