最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get first level children via querySelectorAll(selector) - Stack Overflow

programmeradmin4浏览0评论

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

' > li' is not a valid selector.

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
  • Why should this be done with .querySelectorAll() specifically? Why not .children? – VLAZ Commented Jul 7, 2022 at 17:44
Add a ment  | 

1 Answer 1

Reset to default 11

Use :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)');

发布评论

评论列表(0)

  1. 暂无评论