Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate depth of unordered list

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

For instance, this unordered list deepest li has depth equal with 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>
like image 789
Robin Cox Avatar asked Dec 11 '22 07:12

Robin Cox


1 Answers

Supposing you don't have a selector (id, class etc), you need a simple loop in the 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's greater than maxDepth found yet
    if (cDepth > maxDepth) {

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

// alert
alert(maxDepth);

JSFIDDLE

If you have .myClass selector 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 its ul parents

var depth = $(".myClass").parents("ul").length;
like image 102
Ionică Bizău Avatar answered Dec 28 '22 08:12

Ionică Bizău