siblings()
함수는 DOM 트리 상의 형제 요소들을 찾아 새로운 jQuery 객체를 만들어 줍니다.
이 함수에는 $() 함수에 사용할 수 있는 모든 선택자 표현이 올 수 있습니다. 만일 그 선택자가 주어졌고 그 선택자에 의해 선택될 수 있는 바로 다음 요소들이 있다면 jQuery 객체가 반환되고 그렇지 않다면 제외됩니다.
예를 보시죠.
<ul> <li>list item 1</li> <li>list item 2</li> <li class="third-item">list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul>
item 3의 형제 요소들을 찾아볼까요.
$('li.third-item').siblings().css('background-color', 'red');
스크립트의 결과는 items 1, 2, 4, 그리고 5 의 배경색이 바뀌게 됩니다. 선택자 표현을 포함하지 않았기 때문에 형제 요소들을 모두 선택하게 됩니다. 만일 선택자 표현을 추가하면 다음 요소를 선택하기 전에 선택자에 의한 검증을 실시하게 됩니다.
예 제
노란색 리스트의 형제들을 찾고 개수를 세어 줍니다.
<!DOCTYPE html> <html> <head> <style> ul { float:left; margin:5px; font-size:16px; font-weight:bold; } p { color:blue; margin:10px 20px; font-size:16px; padding:5px; font-weight:bolder; } .hilite { background:yellow; } </style> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <ul> <li>One</li> <li>Two</li> <li class="hilite">Three</li> <li>Four</li> </ul> <ul> <li>Five</li> <li>Six</li> <li>Seven</li> </ul> <ul> <li>Eight</li> <li class="hilite">Nine</li> <li>Ten</li> <li class="hilite">Eleven</li> </ul> <p>Unique siblings: <b></b></p> <script> var len = $(".hilite").siblings() .css("color", "red") .length; $("b").text(len); </script> </body> </html>
예 제
p 태그의 현제들을 찾습니다. 단, "selected"라는 클래스를 사용하는 녀석들만 해당됩니다.
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <div><span>Hello</span></div> <p class="selected">Hello Again</p> <p>And Again</p> <script>$("p").siblings(".selected").css("background", "yellow");</script> </body> </html>