javascript - with - jquery parent child selector



Direct descendants only with jQuery's find() (1)

Is it possible to select only direct descendants of an element using jQuery's find() or children() functions?

I have several ul elements, each with other ul elements inside them, and some root li elements too. I store a specific parent ul in a variable (as a jQuery object) and then look for any of the root li elements within using: my_root_ul.find('li');.

However, this method also finds any li that belongs to the ul inside the ul, if that makes sense.

My question is, how can I select only direct descendants of type li within the my_root_ul object using find(). Ordinarily, we could use something like $('ul > li') to return only direct li elements, but it must be possible to filter down the returned elements?

Here is an example to demonstrate what I mean:

<ul>
    <li>I want this
        <ul>
            <li>I don't want this</li>
            <li>I don't want this</li>
            <li>I don't want this</li>
        </ul>
    </li>
    <li>I want this</li>
    <li>I want this</li>
</ul>

Like this:

my_root_ul.find('> li');

.children() also selects only the immediate children, so you can use that also:

my_root_ul.children('li');




dom