admin管理员组文章数量:1358107
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)');
本文标签: javascriptHow to get first level children via querySelectorAll(selector)Stack Overflow
版权声明:本文标题:javascript - How to get first level children via querySelectorAll(selector) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743946203a2566450.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论