Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find top level li with jQuery

Tags:

jquery

parent

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".

like image 623
gubbfett Avatar asked Aug 28 '13 14:08

gubbfett


2 Answers

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).

like image 167
Frédéric Hamidi Avatar answered Nov 14 '22 16:11

Frédéric Hamidi


Use parents() and last();

 // assuming 'this' is an `li` element:
 var $topLi = $(this).parents('li').last();

Note that jQuery traverses up the DOM, so the last element in the selector will be the top level parent.

like image 40
Rory McCrossan Avatar answered Nov 14 '22 15:11

Rory McCrossan