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>
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With