Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the closest descendants (that matches a selector) with jQuery?

Tags:

jquery

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')?

like image 635
powerboy Avatar asked Nov 05 '22 12:11

powerboy


1 Answers

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;
};
like image 156
Nathan Bubna Avatar answered Nov 12 '22 14:11

Nathan Bubna