Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get first level children via querySelectorAll(selector)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading