How to find nearest descendants (which match a selector) using jQuery?

We can use closest(selector)to find the first ancestor element that matches the selector. It moves up the DOM tree until it finds a match for the selector. But what if I want to travel down the DOM tree until it finds a match for the selector? Is there a jQuery function for this? Or do I need to implement this using a width 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')?

+5
source share
4 answers

Maybe something like this:

$('#main ul:not(#main ul ul)')

- , each() , #main , .

+1

, . :

$.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;
};
+1

Will the elements you want to combine always be a child of the div? If so, you can use the syntax .children ('ul'). It would be better to put Id / Class in a div so you can do the following ...

$('#menu').children('ul');

<div id="main">
    <div id="menu">
        <ul><!-- I want to match this ul -->
            <li>
                <ul><!-- but not this ul -->
                </ul>
            </li>
        </ul>
        <ul><!-- and match this ul -->
        </ul>
    </div>
</div>
0
source

I had the same problem and needed a much more general solution, so I wrote a function for it and decided to pack it as a jQuery plugin . I know this topic is quite old, but please take a look and let me know what you think.

0
source

All Articles