Question

I have a multi-level lists like this:

<ul>
    <li>Item 1
        <ul>
            <li>Item 1's 1st Child
                <ul>
                    <li>Item 1's 1st Grandchild
                        <ul>
                            <li>Item 1's Grand Grandchild</li>
                        </ul>
                    </li>
                    <li>Item 1's 2nd Grandchild</li>
                    <li>Item 1's 3rd Grandchild</li>
                </ul>
            </li>
            <li>Item 1's 2nd Child</li>
            <li>Item 1's 3rd Child</li>
        </ul>
    </li>
    <li>Item 2</li>
</ul>

I want for each li to have class 'level' according to their positions. The result would be like this:

<ul>
    <li class="level-1">Item 1
        <ul>
            <li class="level-2">Item 1's 1st Child
                <ul>
                    <li class="level-3">Item 1's 1st Grandchild
                        <ul>
                            <li class="level-4">Item 1's Grand Grandchild</li>
                        </ul>
                    </li>
                    <li class="level-3">Item 1's 2nd Grandchild</li>
                    <li class="level-3">Item 1's 3rd Grandchild</li>
                </ul>
            </li>
            <li class="level-2">Item 1's 2nd Child</li>
            <li class="level-2">Item 1's 3rd Child</li>
        </ul>
    </li>
    <li class="level-1">Item 2</li>
</ul>

Is there a way to achieve this with jQuery?

Thank you very much for your attention.

Was it helpful?

Solution

Think this is a generic solution:

var current = $('ul:first');
var depth = 1;

while (current.length) {
  current = current.children('li').addClass('level-' + depth++).children('ul');
};

OTHER TIPS

Not the quickest because of DOM traversals, but, you could do it with as little as:

​$("​​​li").each(function() {
   $(this).addClass("level-" + ($(this).parents("li").length+1)); 
});​​​

You can see a working example here

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");

Maybe there's a more programmatic way of doing this & allowing for arbitrary depth, but this was quick.

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) });
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top