JQuery: find(), siblings()

jQuery 2016. 2. 19. 11:10

Tree Traversal 메서드

http://docs.jquery.com/Traversing


Tree Traversal 메서드의 종류

DOM 구조를 이용하는 메서드


.children([selector]) 선택된 개체의 자식 중 Selector 와 동일한 요소를 가져옵니다. 

.closest([selector]) 선택된 개체에서 DOM Tree를 통해 가장 가까운 조상 요소를 가져옵니다. .find([selector]) 선택된 개체에서 selector와 일치하는 요소를 가져옵니다. 

.next([selector]) 선택된 개체에서 selector와 일치하는 형제 요소를 가져옵니다. 일치하는 항목이 없을 경우 다음 항목으로 이동할 요소를 찾는다. 

.parent([selector]) 선택된 개체에서 selector와 일치하는 부모의 요소를 가져옵니다. 

.prev([selector]) 선택된 개체에서 selector와 일치하는 바로 앞의 형제 요소를 가져옵니다.

.siblings([selector]) 선택된 개체에서 selector와 일치하는 형제 요소를 가져옵니다. 자식은 제외한다.


1. find()


$(“div”).filter(“a”) : filter() 메서드를 사용할 경우는 div요소의 집합에서 “a”를 찾는다.

 $(“div”).find(“a”) : find() 메서드를 사용할 경우 div 요소의 집합 내용에서 “a”의 요소를 가져옵니다.


<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script> 

$(document).ready(function () { 

$("div").find("p").css("border", "1px solid red"); 

//$("div").filter("p").css("border", "1px solid red"); 

//$("div").filter(".myClass").css("border", "1px solid red");

 });

</script>

</head>

<body>

<div>

<p>this is 1st p</p>

</div>

<div>

<p>this is 2nd p</p>

</div>

<div class="myClass">

<p>this is 3rd p</p>

</div>

</body>

</html>


find()의 경우 이미 탐색된 개체의 내부 요소에서 selector와 동일한 요소를 가져오며,

filter()의 경우는 처음 탐색 시에 selector에 핬당되는 값으로 탐색을 도와주는 역할




2. .siblings() 

주로 목록에서 마우스로 클릭한 요소만 강조할 경우 매우 쉽게 프로그래밍을 가능하도록 해주는 메서드


예제) 클릭한 행만 빨간색으로 바뀌는 예제

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style>

.selected { background:red }

</style>

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">

$(document).ready(function() {

$("li").each(function() { // li 각각을 가져와(each)

$(this).click(function() { // li 클릭시(click)

$(this).addClass("selected"); // .selected 클래스 적용

$(this).siblings().removeClass("selected"); // 클릭한 li의 형제(siblings) li는 클래스 적용 해제

});

});

});

</script>

</head>

<body>

<div>

<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>

</ul>

</body>

</html>









Posted by netyhobby
,