jQuery chaining parent(), is there an easier way?
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.
精彩评论