Calculate the depth of an unordered list

How can I get the depth of the deepest tag liin an unordered list?

For example, this unordered list is the deepest and lihas a depth equal to 3:

<ul>
  <li></li>
  <li>
    <ul>
      <li></li>
    </ul>
  </li>
  <li>
    <ul>
      <li>
        <ul>
          <li></li> <!-- I am the deepest -->
        </ul>
      </li>
    </ul>
  </li>
</ul>
+4
source share
2 answers

Suppose you don't have a selector (id, class, etc.), you need a simple loop in elements that don't have ul.

// create maxDepth and cDepth variables
var maxDepth = -1
  , cDepth   = -1
  ;

// each `li` that hasn't `ul` children
$("li:not(:has(ul))").each(function() {

    // get the current `li` depth
    cDepth = $(this).parents("ul").length;

    // it greater than maxDepth found yet
    if (cDepth > maxDepth) {

       // this will become the max one
       maxDepth = cDepth;
    }
});

// alert
alert(maxDepth);

JSFIDDLE

If you have a .myClassselector for the deepest li:

<ul>
  <li></li>
  <li>
    <ul>
      <li></li>
    </ul>
  </li>
  <li>
    <ul>
      <li>
        <ul>
          <li class="myClass"></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

it's very simple: just count his parents ul

var depth = $(".myClass").parents("ul").length;
+10
source

you can use as

var parent = $('ul').children(),
child = parent;

while (child.length) {
parent = child;
child = child.children();
}

alert(parent.html());

Demo

Html

<ul >
<li></li>
<li>
  <ul>
  <li></li>
 </ul>
</li>
<li>
<ul>
  <li>
    <ul>
      <li> I am the deepest </li> 
    </ul>
  </li>
 </ul>
  </li>
 </ul>
+1
source

Source: https://habr.com/ru/post/1530582/


All Articles