Finding ancestor with specific attribute or class in jQuery
jquery, jquery-selectors
Solution
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
Problem
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?