开发者

Getting parent id in jquery

开发者 https://www.devze.com 2023-01-10 10:34 出处:网络
I have the following markup: <ul class=\"item\"> <li id=\"user_one\">Username <ul> <li class=\"click\">Click Here</li>

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 a开发者_运维问答lways returns the first item, instead of really the parent from what was clicked.

Any help would be awesome... thanks!


$(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.

0

精彩评论

暂无评论...
验证码 换一张
取 消