We can use closest(selector)
to find the first ancestor element that matches the selector. It travels up the DOM tree until it finds a match for the selector. But what if I want to travels down the DOM tree until it finds a match for the selector? Is there any jQuery function for doing this? Or do I need to implement this using breadth-first search?
Give an example. For the DOM tree below,
<div id="main">
<div>
<ul><!-- I want to match this ul -->
<li>
<ul><!-- but not this ul -->
</ul>
</li>
</ul>
<ul><!-- and match this ul -->
</ul>
</div>
</div>
how to do something like $('#main').closestDescendants('ul')
?
So, the closestChild plugin links are broken for me. Here's an implementation:
$.fn.nearest = function(selector) {
var nearest = $(), node = this, distance = 10000;
node.find(selector).each(function(){
var n = $(this),
d = n.parentsUntil(node).size();
if (d < distance) {
distance = d;
nearest = n;
} else if (d == distance) {
nearest = nearest.add(this);
}
});
return nearest;
};
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