Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - Direct descendants only with jQuery's find()

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>
question from:https://stackoverflow.com/questions/8415003/direct-descendants-only-with-jquerys-find

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...