Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select <li> inside <ul>

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

like image 690
mmu36478 Avatar asked Dec 10 '25 12:12

mmu36478


2 Answers

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>
like image 86
Quentin Avatar answered Dec 12 '25 03:12

Quentin


In jQuery you can use this selector ul > li:not('ul > li > ul > li'):

$("ul > li:not('ul > li > ul > li')").css("background", "green");
ul > li {
  background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    First
    <ul>
      <li>
        Second
        <ul>
          <li>Third</li>
        </ul>
      </li>
      <li>Second</li>
      <li>Second</li>
      <li>Second</li>
    </ul>
  </li>
  <li>First</li>
  <li>First</li>
  <li>First</li>
</ul>
like image 44
Arg0n Avatar answered Dec 12 '25 05:12

Arg0n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!