I have nested lists like this:
<ul>
<li>item 1</li>
<li>item 2
<ul>
开发者_Go百科 <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 only have 3 levels, try this:
$('ul').addClass('level-0');
$('ul').find('ul').removeClass('level-0').addClass('level-1');
$('ul').find('ul').find('ul').removeClass('level-0').removeClass('level-1').addClass('level-2');
http://jsfiddle.net/fallen888/2rATE/
For a more dynamic solution, try this:
$("ul").each(function(index, element) {
var parents = $(this).parents('ul');
var level = -1;
if (parents.length > 0) {
var parentClass = $(parents.get(0)).attr('class');
level = parseInt(parentClass.substr(parentClass.indexOf('level-') + 6, 1));
}
$(this).addClass('level-' + (level + 1));
});
http://jsfiddle.net/fallen888/2rATE/1/
精彩评论