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.
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
Share Improve this question edited Jul 7, 2022 at 17:54 stckvrw asked Jul 7, 2022 at 17:40 stckvrwstckvrw 1,81123 silver badges54 bronze badges 1' > li' is not a valid selector.
-
Why should this be done with
.querySelectorAll()
specifically? Why not.children
? – VLAZ Commented Jul 7, 2022 at 17:44
1 Answer
Reset to default 11Use :scope
let ul = document.createElement('ul');
ul.innerHTML = `
<li>
Item
<ul>
<li>Subitem</li>
</ul>
</li>`;
let items = ul.querySelectorAll(':scope > li');
document.body.appendChild(ul)
console.log(items.length + ' first level item(s)');