I have nested lists like this:
<ul>
<li>item 1</li>
<li>item 2
<ul>
<li>subitem 1</li>
<li>subitem 2</li>
<ul>
<li>sub-subitem1</li>
</ul>
</li>
</ul>
</li>
<li>item 3
<ul>
<li>subitem 1</li>
</ul>
</li>
</ul>
Is there any way I could add a class to the based on their depth level so the output is something like this?
<ul class="level-0">
<li>item 1</li>
<li>item 2
<ul class="level-1">
<li>subitem 1</li>
<li>subitem 2</li>
<ul class="level-2">
<li>sub-subitem1</li>
</ul>
</li>
</ul>
</li>
<li>item 3
<ul class="level-1">
<li>subitem 1</li>
</ul>
</li>
</ul>
I am new to jQuery, have tried this:
$("ul").each(function(index, element){$(element).attr("class", "level-" + index);});
...but it only counts the ul's based on their index. Any help is much appreciated!
Try this:
$('ul').each(function() {
var depth = $(this).parents('ul').length;
$(this).addClass('level-' + depth);
});
See http://jsfiddle.net/alnitak/YSZFm/
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