Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I find a specific parent in jQuery?

The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.

How do I find my nearest parent by class?

Use the closest() method to get the closest parent element by class, e.g. child. closest('. parent') . The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.

What does parent () do in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

Where can I find grandparents in jQuery?

jQuery parentsUntil() Method The parentsUntil() method returns all ancestor elements between the selector and stop. An ancestor is a parent, grandparent, great-grandparent, and so on.


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.


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.


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.


Extracted from @Resord's comments above. This one worked for me and more closely inclined with the question.

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

Thanks


<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 situation, i use this code:

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

Hope this help someone.