How to find a parent with a known class in jQuery?

How to find a parent with a known class in jQuery?

I have a

that has many other

s within it, each at a different nesting level. Rather than give every child

an identifier, I rather just give the root

the identifier. Here’s an example:

If I write a function in jQuery to respond to class d and I want to find the ID for its parent, class a, how would I do this?
I cannot simply do $(‘.a’).attr(‘id’);, because there are multiple class as. I could find its parent’s parent’s parent’s ID but that seems of poor design, slow, and not very polymorphic (I would have to write different code for finding the ID for class c).

Solutions/Answers:

Solution 1:

Assuming that this is .d, you can write

$(this).closest('.a');

The closest method returns the innermost parent of your element that matches the selector.

Solution 2:

Pass a selector to the jQuery parents function:

d.parents('.a').attr('id')

EDIT Hmm, actually Slaks’s answer is superior if you only want the closest ancestor that matches your selector.

Related:  Possible to detect if a user has multiple tabs of your site open?

Solution 3:

You can use parents() to get all parents with the given selector.

Description: Get the ancestors of each
element in the current set of matched
elements, optionally filtered by a
selector.

But parent() will get just the first parent of the element.

Description: Get the parent of each
element in the current set of matched
elements, optionally filtered by a
selector.

jQuery parent() vs. parents()

And there is .parentsUntil() which I think will be the best.

Description: Get the ancestors of each
element in the current set of matched
elements, up to but not including the
element matched by the selector.

Solution 4:

Use .parentsUntil()

$(".d").parentsUntil(".a");