简体   繁体   English

嵌套<ul>结构体。 仅循环通过顶层<li>元素</li></ul>

[英]Nested <ul> structure. Loop only through the top level <li> elements

I have the following HTML structure:我有以下 HTML 结构:

<ul>

  <li></li> <!-- First element top-level element -->

  <li></li> <!-- Second element top-level element -->

  <ul>
    <li></li>
    <li></li>
  </ul>

  <li></li> <!-- Third element top-level element -->

  <ul>
    <li></li>
    <li></li>
  </ul>

</ul>

How can I select and loop only through the top-level <li> elements of the first ul structure?我怎样才能 select 并仅循环通过第一个ul结构的顶级<li>元素? (should do 3 loops) . (应该做3个循环) I tried the following, but that loops through all <li> elements (7 loops) .我尝试了以下方法,但循环遍历所有<li>元素(7 loops)

var li_elements = cat_tree
  .getElementsByTagName("ul")[0]
  .getElementsByTagName("li");

for (let element of li_elements) {
  // Do Some Awesome Code Here
}

Use a child selector instead of getElementByTagName.使用子选择器而不是 getElementByTagName。

I don't know the parent structure, but give this a try.我不知道父结构,但试试这个。

var li_elements = cat_tree.querySelectorAll("ul:first-child > li");

with querySelectorAll you get a nodelist to apply foreach() method like a array使用 querySelectorAll 你会得到一个节点列表来像数组一样应用 foreach() 方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM