Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 611
Gruber Avatar asked May 02 '12 11:05

Gruber


2 Answers

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
like image 103
Rory McCrossan Avatar answered Oct 18 '22 18:10

Rory McCrossan


Only class solution is presented, but not the attribute one.

I found my answer here: jQuery find closest parent link with attribute

like image 4
em2 Avatar answered Oct 18 '22 20:10

em2