开发者

jQuery chaining parent(), is there an easier way?

开发者 https://www.devze.com 2023-01-19 23:41 出处:网络
Hay, I have some markup like this <div id=\"some-id\"> <h2><a href=\"#\">Title</a></h2>

Hay, I have some markup like this

<div id="some-id">
    <h2><a href="#">Title</a></h2>
</div>

and some jQuery like this

$(this).parent().parent().attr("id")

$(this) is referring to the 'a' tag within the 'h2'

Is there an easier 开发者_如何学JAVAway to select the parent div without using parent() twice. I tried

$(this).parent("div").attr("id")

but it didn't work.

Thanks


You can use .closest(), like this:

$(this).closest("div").attr("id")

You can test it here. .parent("div") isn't as intuitive as it seems, it gets only the immediate parent if it matches the selector, .closest() climbs the parents until it matches the selector.

Please note that (doesn't apply to this example) if this matches the selector, it returns that element, it doesn't start with the first parent, it starts with itself.

0

精彩评论

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