Home > Software design >  How to get first level children via querySelectorAll(selector)
How to get first level children via querySelectorAll(selector)

Time:07-08

If we have a UL list with nested UL lists like

<ul>
    <li>Item
        <ul>
            <li>Subitem</li>
        </ul>
    </li>
</ul>

and we need to get all the LI elements of the first level only, we can use querySelectorAll() the way like:

let firstLevelChildren = document.querySelectorAll('ul > li');

But what if I create the UL list via document.createElement('ul') and need to get the first level children of such specific node via querySelectorAll(selector)?

Is there a selector?

I know about node.children, but I need a way via querySelectorAll().

There may be any unknown number of the first level children. Also there may be different cases like '> li > ul' and so on.

The way like:

let ul = document.createElement('ul');
ul.innerHTML = '<li>Item<ul><li>Subitem</li></ul></li>';
let items = ul.querySelectorAll('> li');
console.log(items);

throws the error

' > li' is not a valid selector.

CodePudding user response:

Use :scope

let ul = document.createElement('ul');
ul.innerHTML = '<li>Item<ul><li>Subitem</li></ul></li>';
let items = ul.querySelectorAll(':scope >   li');
console.log(items.length);

  • Related