In my javascript experience, I found that is a very common task "searching the nearest ancestor of an element with some condition (tag name, class,...)". Can the parents() method of jquery do the job? The order of returned elements of parents() is predictable? Is top-to-bottom or bottom-to-top? For the moment I use this utility function:
function ancestor(elem, selector) {
var $elem = $( elem ).parent();
while( $elem.size() > 0 ) {
if( $elem.is( selector ) )
return $elem;
else
$elem = $elem.parent();
}
return null;
}
Can someone tell me if there is a clever way to do the job?
The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverse upwards from the current element in the search of first ancestor of the element.
jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.
The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.
The closest() method searches up the DOM tree for elements which matches a specified CSS selector. The closest() method starts at the element itself, then the anchestors (parent, grandparent, ...) until a match is found. The closest() method returns null() if no match is found.
Edit: Since jQuery 1.3, this has been built in as the closest()
function. eg: $('#foo').closest('.bar');
yep - parents() traverses up the tree.
<div id="a">
<div id="b">
<p id="c">
<a id="d"></a>
</p>
</div>
</div>
$('#d').parents("div:first");
will select div b.
Adding to @nickf's answer:
jQuery 1.3 simplifyed this task with closest
.
Given a DOM:
<div id="a">
<div id="b">
<p id="c">
<a id="d"></a>
</p>
</div>
</div>
You can do:
$('#d').closest("div"); // returns [ div#b ]
[Closest returns a] set of elements containing the closest parent element that matches the specified selector, the starting element included.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With