views:

93

answers:

2

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

A: 

Will the elements you want to match always be a child of a div? If so, you could match using .children('ul') syntax. It would be best to put a Id/Class on the div, so you could 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>
Zachary
@Zachary - level difference between $('#main') and its closest ul descendants can vary, and only $('#main') have determinate id.
powerboy
A: 

Something like this might suffice:

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

If you need something more accurate then you can use each() to iterate the list of elements, calculate the shortest path to #main, and filter out those elements where the path is longer than this.

CurtainDog