Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding level depth to class of nested lists

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!

like image 526
John O'Connor Avatar asked Feb 24 '23 20:02

John O'Connor


1 Answers

Try this:

$('ul').each(function() {
    var depth = $(this).parents('ul').length;
    $(this).addClass('level-' + depth);
});

See http://jsfiddle.net/alnitak/YSZFm/

like image 178
Alnitak Avatar answered Feb 26 '23 09:02

Alnitak