Is there a way to automatically add classes to multilevel lists using jQuery?
I have multilevel lists like this:
<ul>
<li>Item 1
<ul>
<li>Item 1 1st Child
<ul>
<li>Item 1 1st Grandchild
<ul>
<li>Item 1 Grand Grandchild</li>
</ul>
</li>
<li>Item 1 2nd Grandchild</li>
<li>Item 1 3rd Grandchild</li>
</ul>
</li>
<li>Item 1 2nd Child</li>
<li>Item 1 3rd Child</li>
</ul>
</li>
<li>Item 2</li>
</ul>
I want everyone to li
have a "level" class according to their positions. The result will be like this:
<ul>
<li class="level-1">Item 1
<ul>
<li class="level-2">Item 1 1st Child
<ul>
<li class="level-3">Item 1 1st Grandchild
<ul>
<li class="level-4">Item 1 Grand Grandchild</li>
</ul>
</li>
<li class="level-3">Item 1 2nd Grandchild</li>
<li class="level-3">Item 1 3rd Grandchild</li>
</ul>
</li>
<li class="level-2">Item 1 2nd Child</li>
<li class="level-2">Item 1 3rd Child</li>
</ul>
</li>
<li class="level-1">Item 2</li>
</ul>
Is there a way to achieve this using jQuery?
Thank you very much for your attention.
+2
a source to share
4 answers
Assuming you only have 4 levels of lists
$("ul > li").addClass("level-1");
$("li.level-1 > ul > li").addClass("level-2");
$("li.level-2 > ul > li").addClass("level-3");
$("li.level-3 > ul > li").addClass("level-4");
There might be a more programmatic way to do this and allow arbitrary depth, but it was fast.
+2
a source to share
I'll play ... you can always make it recursive :)
$(function() {
addLevel($('ul:first'));
});
function addLevel($ul, level) {
( ! level ) ? level = 1 : level += 1;
$ul.children('li').each(function() {
$(this).addClass('level-' + level);
$(this).children('ul').each(function() { addLevel($(this), level) });
});
}
0
a source to share