parents()
http://api.jquery.com/parents/
선택된 엘리먼트의 모든 부모 엘리먼트 요소를 가지오게 된다.
예)
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>parents demo</title> <style> p, div, span { margin: 2px; padding: 1px; } div { border: 2px white solid; } span { cursor: pointer; font-size: 12px; } .selected { color: blue; } b { color: red; display: block; font-size: 14px; } </style> <script src="//code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <p> <div> <div><span>Hello</span></div> <span>Hello Again</span> </div> <div> <span>And Hello Again</span> </div> </p> <b>Click Hellos to toggle their parents.</b> <script> function showParents() { $( "div" ).css( "border-color", "white" ); var len = $( "span.selected" ) .parents( "div" ) .css( "border", "2px red solid" ) .length; $( "b" ).text( "Unique div parents: " + len ); } $( "span" ).click(function() { $( this ).toggleClass( "selected" ); showParents(); }); </script> </body> </html>
.closest() |
.parents() |
---|---|
Begins with the current element | Begins with the parent element |
Travels up the DOM tree until it finds a match for the supplied selector | Travels up the DOM tree to the document’s root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied |
The returned jQuery object contains zero or one element for each element in the original set, in document order | The returned jQuery object contains zero or more elements for each element in the original set, in reverse document order |
closest()
http://api.jquery.com/closest/
반복되는 엘리먼트 안에 요소 자체를 테스트하고 DOM 트리에 조상을 통해 통과하여 일치하는 첫 번째 요소를 선택한다.
즉, 실행된 엘리먼트의 가장 가까운 엘리먼트 요소만 선택이 되는 것입니다.
예)
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>closest demo</title> <style> li { margin: 3px; padding: 3px; background: #EEEEEE; } li.hilight { background: yellow; } </style> <script src="//code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <ul> <li><b>Click me!</b></li> <li>You can also <b>Click me!</b></li> </ul> <script> var listElements = $( "li" ).css( "color", "blue" ); $( document ).on( "click", function( event ) { $( event.target ).closest( listElements ).toggleClass( "hilight" ); }); </script> </body> </html>
답글 남기기