Robin Cox
Robin Cox

Reputation: 1490

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>

Upvotes: 4

Views: 6336

Answers (2)

Ionică Bizău
Ionică Bizău

Reputation: 113375

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;

Upvotes: 12

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

you can use like

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>

Upvotes: 1

Related Questions