did1k
did1k

Reputation: 165

Is there a way to automatically add classes in multi-level lists with jQuery?

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.

Upvotes: 2

Views: 731

Answers (4)

Matt
Matt

Reputation: 75317

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');
};

Upvotes: 2

David
David

Reputation: 1927

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

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630429

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

Upvotes: 3

Quasipickle
Quasipickle

Reputation: 4498

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.

Upvotes: 2

Related Questions