Search code examples
jqueryparent

Find top level li with jQuery


Let's say i have a menu like this...

<ul class="main_menu">
    <li class="item-1">
        First top level item
        <ul>
            <li class="item-2">Item 2</li>
            <li class="item-3">
                Item 3
                <ul>
                    <li class="item-4">Item 4</li>
                    <li class="item-5">Item 5</li>
                </ul>
            </li>
            <li class="item-6">Item 6</li>
        </ul>
    </li>
    <li class="item-7">
        Second top level item
        <ul>
            <li class="item-8">Item 8</li>
            <li class="item-9">Item 9</li>
            <li class="item-10">Item 10</li>
            <li class="item-11">Item 11</li>
        </ul>
    </li>
</ul>

...and in this case the sub menus can be at variable depth, how can i get the top level item if i only know an sub item? For example, i know the class item-5, then i want to get the class "item-1", or if i know the "item-11", i want "item-7".

That is, wherever i am, i want the "Top level item X".


Solution

  • You can chain parents() into last():

    var topListItem = $(".item-5").parents("li").last();
    

    This solution works because parents() returns the ancestor elements ordered from the closest to the outer ones.

    If you want the original element to be part of the search (i.e. .item-7 returning itself), then you can chain parents() into addBack(), then into first():

    var topListItem = $(".item-7").parents("li").addBack().first();  // '.item-7'
    

    addBack() adds the original element back into the chain of parents. In this case, we have to apply first() instead of last() because addBack() puts the elements in document order (so the top-level element will be the first one matched instead of the last).