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

1

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

Embark answered 13/10, 2010 at 9:2 Comment(0)
M
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.

Mccraw answered 13/10, 2010 at 9:3 Comment(2)
Does .closest() move up only? Or will it move down as well?Embark
@Embark - 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.Mccraw

© 2022 - 2024 — McMap. All rights reserved.