views:

49

answers:

4
<li id="someID">
    <div id="div1">Text</div>
    <div id="div2">Text x 2</div>
    <div id="div3">Text x 3</div>
        <span>
            <div>
                <ul>
                    <li class="menuItem">Menu Item</li>
                </ul>
            </div>
        </span>
</li>

In short, I'm trying to find the ID "someID" when the class "menuItem" is clicked. The code below doesn't seem to be cutting it.

$('.menuItem').click(function(){alert($(this).closest('li').attr('id'));});
+1  A: 

If you want the parent then you could use .parent which is documented here

griegs
+1  A: 

you can use .parent

.parents("li") so it will return the li parent
guy schaller
+5  A: 

instead of .closest('li'). use the .parents('li'). (note the plural)

It is even mentioned at the closest() documentation ..

Gaby
For the original questioner: http://api.jquery.com/closest/ gives a good explanation of the differences between closest() and parents(). Note that while parents() can return multiple elements, the closest one will be the first one in the collection; and when you use .attr() on a collection with multiple elements, it returns the attribute from the first one in the collection.
Carson63000
+2  A: 

Another approach is to put a class on the li you are trying to identify, and make the .closest() selector more precise.

e.g.

<li class="master" id="someID">
    <div id="div1">Text</div>
    <div id="div2">Text x 2</div>
    <div id="div3">Text x 3</div>
        <span>
            <div>
                <ul>
                    <li class="menuItem">Menu Item</li>
                </ul>
            </div>
        </span>
</li>

$('.menuItem').click(function(){alert($(this).closest('li.master').attr('id'));});
Carson63000