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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With