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?
Use
closest(). it will traverse up the DOM from the current element until it finds a parent element matching the selector you provide.