Coder Perfect

In jQuery, how can I find a parent with a known class?

Problem

I have a div> that contains a slew of other div>s, each at a different nesting level. Rather than assigning an identification to each child div>, I assign the identifier to the root div>. Here’s an illustration:

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

How would I find the ID for class a’s parent, class d, if I wrote a jQuery method to react to class d?

Because there are numerous classes as, I can’t just perform $(‘.a’).attr(‘id’);. I was able to locate its parent’s parent’s parent’s ID, however it appears to be poorly designed, sluggish, and polymorphic (I would have to write different code for finding the ID for class c).

Asked by John Smith

Solution #1

If the extension is.d, you can write

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

The innermost parent of your element that fits the selection is returned by the closest method.

Answered by SLaks

Solution #2

To use the jQuery parents function, pass a selector:

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

EDIT Actually, Slaks’ response is better if you simply want the ancestor who is closest to your selector.

Answered by Drew Noakes

Solution #3

You can acquire all parents with the specified selector by calling parents().

However, parent() will only return the element’s first parent.

parents vs. parent() in jQuery ()

There’s also.parentsUntil(), which I believe is the better option.

Answered by Amr Elgarhy

Solution #4

Excerpted from @Resord’s above comments. This one was more in line with the question and worked for me.

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

Thanks

Answered by Anjana Silva

Solution #5

<div id="412412412" class="input-group date">
     <div class="input-group-prepend">
          <button class="btn btn-danger" type="button">Button Click</button>
          <input type="text" class="form-control" value="">
      </div>
</div>

In my case, I use the following code:

$(this).parent().closest('.date').attr('id')

I hope this information is useful to someone.

Answered by Huy

Post is based on https://stackoverflow.com/questions/5333426/how-to-find-a-parent-with-a-known-class-in-jquery