views:

34

answers:

1

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

+6  A: 

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
Does .closest() move up only? Or will it move down as well?
dotty
@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