Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  115] [ 3]  / answers: 1 / hits: 24172  / 7 Years ago, mon, june 5, 2017, 12:00:00

Assume I have html structure as



ul
li //this one
ul
li
li
li
li //this one


I don't want to get all li's.
As I commented I just want to get first segment li's. How can I select them?



document.querySelectorAll(ul > li);


returns all li's.



edit: actually this is just a snippet of the tree.

I can't modify the structure as adding class or id. I'm looking for an answer to get the list of first layer lis


More From » html

 Answers
47

You need to select all the li items where the grandparent is not another list item.



:not(li) > * > li {}


This will only work if you don't have extra elements in the markup.



For example it would fail with:



<ul>
<li>
<div>
<ul>
<li>


A slower, but more reliable, approach would be to get all the list items and then filter out ones which had list item ancestors.





var lis = document.getElementsByTagName('li');
var lis_without_li_ancestors = [];
for (var i = 0; i < lis.length; i++) {
var element = lis[i];
if (!has_li_ancestor(element)) {
lis_without_li_ancestors.push(element);
}
}

console.log(lis_without_li_ancestors);

function has_li_ancestor(element) {
var parent = element.parentNode;
if (parent.tagName.toLowerCase() === body) {
return false;
} else if (parent.tagName.toLowerCase() === li) {
return true;
} else {
return has_li_ancestor(parent);
}
}

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




[#57563] Thursday, June 1, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
magaly

Total Points: 524
Total Questions: 96
Total Answers: 89

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
;