dzm
dzm

Reputation: 23534

Getting parent id in jquery

I have the following markup:

<ul class="item">
      <li id="user_one">Username
          <ul>
            <li class="click">Click Here</li>
        </ul>

Basically I want to be able to get the ID of the parent LI. This is what I currently have:

$(this).parents("ul").find(".item li").attr("id");

This works sort of, there are many of these lists on a single page, all with different ID's. It always returns the first item, instead of really the parent from what was clicked.

Any help would be awesome... thanks!

Upvotes: 1

Views: 1778

Answers (1)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

$(this).parent().closest('li').attr('id')

I chose this way over parents because:

[.parents] Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied

Which to me means it will get all the elements before it is filtered, but closest will return the first element it finds.

Upvotes: 1

Related Questions