I have the following HTML structure:
<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? (should do 3 loops) . I tried the following, but that loops through all <li>
elements (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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.