7

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 way to select the parent div without using parent() twice. I tried

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

but it didn't work.

Thanks

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
dotty
  • 40,405
  • 66
  • 150
  • 195

1 Answers1

18

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.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • Does .closest() move up only? Or will it move down as well? – dotty Oct 13 '10 at 09:08
  • 1
    @dotty - It only goes to parents, if you want to find children use `.find()`, though you can only have one parent path, children can have many branches...so depends what you're after. – Nick Craver Oct 13 '10 at 09:10