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.
var ancestorByClass = $(elem).closest(".myClass"); // by class
var ancestorByAttribute = $(elem).closest('[href="#foo"]'); // by attribute
Only class solution is presented, but not the attribute one.
I found my answer here: jQuery find closest parent link with attribute
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