Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Child selector using `querySelectorAll` on a DOM collection

Let's presume you got a list with nested child lists.

<ul>
    <li></li>
    <li>
        <ul>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li></li>
</ul>

And use document.querySelectorAll() to make a selection:

var ul = document.querySelectorAll("ul");

How can i use the ul collection to get the direct child elements?

ul.querySelectorAll("> li"); 
// Gives 'Error: An invalid or illegal string was specified'

Let's presume ul is cached somehow (otherwise i could have done ul > li directly).

In jQuery this works:

$("ul").find("> li");

But it doesn't in native querySelectorAll. Any solutions?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The correct way to write a selector that is "rooted" to the current element is to use :scope.

ul.querySelectorAll(":scope > li");

See my answer here for an explanation and a robust, cross-browser solution: https://stackoverflow.com/a/21126966/1170723


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...