'Finding ancestor with specific attribute or class in jQuery
I have a DOM element elem that has an ancestor element which has the class myClass (alternatively an attribute with some name). The problem is that I need to find this ancestor easily with jQuery. Currently, I am stuck with ugly trial-and-error stuff like
var ancestor = $(elem).parent().parent().parent().parent().parent().parent().parent();
If the HTML code changes, the jQuery code easily breaks.
Is it possible to find the ancestor element with more elegant jQuery code?
Solution 1:[1]
Only class solution is presented, but not the attribute one.
I found my answer here: jQuery find closest parent link with attribute
Solution 2:[2]
New method added by jQuery, the parents function allows you to check for all parents with selectors.
var ancestor = $(elem).parents(".myClass");
Solution 3:[3]
Try
var ancestor = $(elem).closest(selector what are you looking for);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | Sunny R Gupta |
| Solution 3 | bitoshi.n |
