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

John Smith picture John Smith · Mar 17, 2011 · Viewed 272.4k times · Source

I have a <div> that has many other <div>s within it, each at a different nesting level. Rather than give every child <div> an identifier, I rather just give the root <div> the identifier. Here’s an example:

<div class="a" id="a5">
  <div class="b">
    <div class="c">
      <a class="d">
      </a>
    </div>
  </div>
</div>

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).

Answer

SLaks picture SLaks · Mar 17, 2011

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.