[jQuery] Traversing

Traversing


Traversing에 나열되어 있는 jQuery 메서드들은 jQuery의 선택자를 기준으로 하여 새로운 노드를 찾아가는 방법을 제공한다.



1. 트리 구조 탐색(Tree Traversal)

DOM에 접근하여 원하는 노드를 찾는 방법을 제공한다. 즉, DOM Tree 구조를 기반으로 찾아가는 방식이다. 이 방법을 잘 활용하며 DOM에 id나 class를 최소한으로 사용할 수 있다.

선택한 노드를 기준으로 형제, 자식, 부모 등으로 접근하는 다양한 방법이 있다.

ex.)

jQuery('li).parent().css('background-color','red');

// parent() 메서드는 현재 지정된 li의 부모 노드를 의미한다. 따라서 li 노드들의 부모를 선택하여 배경색을 빨간색을 설정한다.


 메서드

  설 명

 children()

 선택된 노드의 모든 자식노드만 선택한다.

 find()

 선택한 노드의 자손 노드 중 조건에 맞는 노드를 선택한다.

 next()

 선택한 노드의 다음 노드를 선택한다.

 nextAll()

 선택한 노드의 다음 모든 노드를 선택한다.

 parent()

 선택한 노드의 노드를 선택한다.

 parents()

 선택한 노드의 모든 부모 노드를 선택한다.

 prev()

 선택한 노드의 이전 노드를 선택한다.

 prevAll()

 선택한 노드의 모든 이전 노드를 선택한다.

 closest()

 선택한 노드를 포함하면서 가장 가까운 상위 노드를 선택한다.

 nextUntil()

 다음에 위치한 노드를 조건에 맞을 때까지 찾는다.

 parentsUntil()

 조건이 참이 될 때까지 부모 노드를 찾는다.

 prevUntil()

 이전에 위치한 노드를 조건에 맞을 때까지 찾는다.

 siblings()

 형제 노드들을 모두 찾는다.


$("div#container").children("p")

div#container 태그의 자식 태그들 중에서 <p> 태그를 모두 선택한다. 여기서 주의할 점은 자손 레벨에서 찾지 않고 자식 레벨에서만 찾는다는 것이다.

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>children</title>

<!-- jQuery library -->

<script src="jquery-1.7.2.min.js"></script>

<style>

div,p {

float: left;

margin: 10px;

background-color: #FFF;

}


div#sub {

width: 80px;

height: 80px;

border: #000 thin solid;

}


p {

width: 50px;

height: 50px;

border: #000 thin solid;

}

</style>

</head>

<body>

<div id="container">

<div id="sub">

<p>div p</p>

</div>

<p>p</p>

<p>p</p>

</div>

<!---------- jQuery code Start ---------->

<script>

$("div#container").children("p").css("background-Color", "yellow");

</script>

</body>

</html>


$('div#container').find('p')

<div> 태그의 자손 태그들 중에서 <p> 태그를 모두 찾아 선택한다. children()과 find()의 차이점은 자식까지 찾느냐, 자손까지 찾느냐이다.

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>find</title>

<!-- jQuery library -->

<script src="jquery-1.7.2.min.js"></script>

<style>

div,p {

float: left;

margin: 10px;

background-color: #FFF;

}


div#sub {

width: 80px;

height: 80px;

border: #000 thin solid;

}


p {

width: 50px;

height: 50px;

border: #000 thin solid;

}

</style>

</head>

<body>

<div id="container">

<div id="sub">

<p>div p</p>

</div>

<p>p</p>

<p>p</p>

</div>

<!---------- jQuery code Start ---------->

<script>

$("div#container").find("p").css("background-Color", "yellow");

</script>

</body>

</html>


$('p#part1').prev()

id 값이 part1인 <p> 태그의 바로 앞에 위치한 노드를 선택한다. 매개 변수로 찾고 싶은 노드를 전달할 수도 있다.

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Traversal- prev</title>

<!-- jQuery library -->

<script src="jquery-1.7.2.min.js"></script>

<style>

div,p {

float: left;

margin: 10px;

background-color: #FFF;

}


div#sub {

width: 80px;

height: 80px;

border: #000 thin solid;

}


p {

width: 50px;

height: 50px;

border: #000 thin solid;

}

</style>

</head>

<body>

<div id="container">

<div id="sub">

<p>div p</p>

</div>

<p id="part1">p</p>

<p>p</p>

<p>p</p>

</div>

<!---------- jQuery code Start ---------->

<script>

$("p#part1").prev().css("background-Color", "yellow");

</script>

</body>

</html>


$('p#part1').next()

id 값이 part1인 <p> 태그의 다음에 위치한 노드를 선택한다. 매개 변수로 찾고 싶은 노드를 전달할 수도 있다.

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Traversal- next</title>

<!-- jQuery library -->

<script src="jquery-1.7.2.min.js"></script>

<style>

div,p {

float: left;

margin: 10px;

background-color: #FFF;

}


div#sub {

width: 80px;

height: 80px;

border: #000 thin solid;

}


p {

width: 50px;

height: 50px;

border: #000 thin solid;

}

</style>

</head>

<body>

<div id="container">

<div id="sub">

<p>div p</p>

</div>

<p id="part1">p</p>

<p>p</p>

<p>p</p>

</div>

<!---------- jQuery code Start ---------->

<script>

$("p#part1").next().css("background-Color", "yellow");

</script>

</body>

</html>


$('p'#part1').siblings()

id 값이 part1인 <p> 태그의 형제 노드를 선택한다. 매개 변수로 찾고 싶은 노드를 전달할 수도 있다.

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Traversal- siblings</title>

<!-- jQuery library -->

<script src="jquery-1.7.2.min.js"></script>

<style>

div,p {

float: left;

margin: 10px;

background-color: #FFF;

}


div#sub {

width: 80px;

height: 80px;

border: #000 thin solid;

}


p {

width: 50px;

height: 50px;

border: #000 thin solid;

}

</style>

</head>

<body>

<div id="container">

<div id="sub">

<p>div p</p>

</div>

<p id="part1">p</p>

<p>p</p>

<p>p</p>

</div>

<!---------- jQuery code Start ---------->

<script>

$("p#part1").siblings().css("background-Color", "yellow");

</script>

</body>

</html>

$('p#part1').parent()

id 값이 part1인 <p> 태그의 부모 노드를 선택한다.

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>parent</title>

<!-- jQuery library -->

<script src="jquery-1.7.2.min.js"></script>

<style>

div,p {

float: left;

margin: 10px;

background-color: #FFF;

}


div#sub {

width: 80px;

height: 80px;

border: #000 thin solid;

}


p {

width: 50px;

height: 50px;

border: #000 thin solid;

}

</style>

</head>

<body>

<div id="container">

<div id="sub">

<p>div p</p>

</div>

<p id="part1">p</p>

<p>p</p>

<p>p</p>

</div>

<!---------- jQuery code Start ---------->

<script>

$("p#part1").parent().css("background-Color", "yellow");

</script>

</body>

</html>


2. 필터링

선택된 집합에서 다시 조건에 맞는 jQuery 집합을 선택한다.


 메소드

 설 명

 eq()

 인덱스 번호에 해당하는 노드를 찾습니다. index 0은 첫 번째 노드를 의미한다.

 filter()

 선택된 노드 집합에서 선택자를 추가하거나 함수를 사용하여 원하는 결과를 추출해낼 수 있다.

 first()

 선택된 노드 집합에서 첫 번째 자식 노드를 찾는다.

 has()

 선택된 요소들이 자신의 자식 요소에서 주어진 선택자가 있는지를 확인하여  범위를 축소한다.

 is()

 매개 변수로 selector, element, jQuery를 입력하여 입력한 객체가 있으면 true를 반환한다.

 last()

 선택된 노드 집합을 변경한다.

 map()

 대상이 되는 노드 집합을 변경한다.

 not()

 조건에 맞지 않는 것들만 찾아서 선택한다.

 slice()

 선택된 집합을 조건의 범위로 재선택한다. 배열의 slice()와 같은 기능이다.


<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Filtering</title>

<!-- jQuery library -->

<script src="jquery-1.7.2.min.js"></script>

<style>

div,p {

float: left;

margin: 10px;

background-color: #FFF;

}


div#sub {

width: 80px;

height: 80px;

border: #000 thin solid;

}


div.middle {

width: 80px;

height: 80px;

border: #000 thin solid;

}


p {

width: 50px;

height: 50px;

border: #000 thin solid;

}

</style>

</head>

<body>

<div id="main">

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

<p>p</p>

<p>p</p>

<p>p</p>

<p>p</p>

<div id="sub">

<p>div p</p>

</div>

</div>

<!---------- jQuery code Start ---------->

<script>

// 한줄씩 주석으로 처리해가며 확인하여 보세요

$("div#main p").first().css("background-Color", "yellow");

// $("div#main p").last().css("background-Color","yellow");

// $("div#main p").eq(1).css("background-Color","yellow");

// $("div#main div").filter(".middle").css("background-Color","yellow");

// $("div#main div").not(".middle").css("background-Color","yellow");

  // $('div').has('p').css("background-Color","yellow");

</script>

</body>

</html>


$("div#main p").first()

id가 main인 <div> 태그의 첫 번째 <p> 태그를 선택한다.


$("div#main p").last()

id가 main인 <div> 태그의 마지막 <p> 태그를 선택한다.


$("div#main p").eq(1)

id가 main인 <div> 태그의 두 번째 <p> 태그를 선택한다. 인덱스는 0부터 시작한다.



$("div#main div").filter(".middle")

<div> 태그 중에서 클래스 속성 값이 middle인 것을 선택한다.


$("div#main div").not(".middle")

<div> 태그 중에서 클래스 속성 값이 middle이 아닌 것을 선택한다.


$('div').has('p')

<div> 태그 자손 중에 <p> 태그가 있는 <div> 태그를 선택한다.


cf.) Selectors의 :first와 Traversing의 first()는 어떤 차이가 있나?

선택된 집합에서 첫 번째 노드를 반환하는 데에는 차이가 없다. 단지 Selector의 :first 보다 Traversing의 first()가 더 최신 버전이기 때문에 필터링 속도가 빠르고 여러 가지 메서드를 연속해서 나열할 수 있는 메서드 체인 방식의 표기에 더 적합하다.

- Selectors의 :first

$("div").click(fn);

$("div:first").css("background-color", "red");


- Traversing의 first()

$("div").click(fn).first().css("background-color", "red");


cp.) find() 메서드를 이용한 chain

chain의 대상을 바꿔서 체인을 계속 연장시킬 수 있는 방법

--> traversing을 이용해서 chain안에서 대상을 움직일 수 있다.

- http://api.jquery.com/category/traversing/

- taeyo.net jQuery traverse 강좌

- 너무 복잡한 chain은 코드의 가독성을 떨어 뜨릴 수 있다.


예제. traversing을 이용해서 chain안에서 대상을 움직일 수 있다.

<html>

    <body>

        <ul class="first">

            <li class="foo"> list item 1 </li>

            <li> list item 2 </li>

            <li class="bar"> list item 3 </li>

        </ul>

        <ul class="second">

            <li class="foo"> list item 1 </li>

            <li> list item 2 </li>

            <li class="bar"> list item 3 </li>

        </ul>

        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

        <script type="text/javascript">$('ul.first').find('.foo').css('background-color', 'red').end().find('.bar').css('background-color', 'green');</script>

    </body>

</html>

ul.first 엘리먼트 중에서 .foo를 찾아라, 찾은 다음 

-traversing(탐색): ul.first 선택자가 find()를 통해서 chain Context(제어의 대상)가 변경되는 것을 말함

end():chain context를 유지하다가 마지막으로 사용한 traversing을 취소하게 된다.

end()라는 메소드를 시작하기 전에는 li엘리먼트가 지정되었으나 end()메소드가 지정되고 나서는 find로 지정한 것이 취소가 되고

ul 엘리먼트로 chain context가 전환되었다는 것을 의미

--> 탐색 기능을 이용하면 하나의 context에서 필요에 따라 제어하고자 하는 대상을 변경할 수 있다. 


3. 다양한 탐색(Miscellaneous Traversing)

.contents() 

선택한 요소의 자식 요소를 가져온다.(text node 포함)

$('.container').contents().filter(function(){}); 

// class container 요소의 자식요소(text 포함)를 가져와 filter 한다. iframe text를 가져올때 사용


.add() 

요소를 추가 선택한다. 

$("p").add("div")  // p 요소와 div 요소를 선택한다.


.end()

jQuery 함수를 연쇄적으로(chain)으로 사용할 경우 앞쪽에 이미 선택되었던 요소로 돌아간다.

 $('ul:first').find('.foo).css('background-color' , 'red')  // ul의 첫번째 요소에서 class=foo를 찾아 배경 변경

 .end().find('bar').css('background-color', 'green'); // find를 호출하기 전의 요소($('ul:first))에서 class=bar를 찾아 배경 변경


.andSelf() 

선택된 구조 요소를 이어붙인다.

$('div').find('p').andSelf().css(..);  

// div와 내부의 p요소를 선택해서 결합 후 css 적용

'WebFont-end > jQuery' 카테고리의 다른 글

[jQuery] Event  (0) 2014.12.07
[jQuery] Attribute/CSS  (0) 2014.12.07
[jQuery] DOM Manipulation  (0) 2014.12.07
[jQuery] Wrapper  (0) 2014.12.07
[jQuery] Selector  (0) 2014.11.29