8

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?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Gruber
  • 4,478
  • 6
  • 47
  • 74

4 Answers4

15

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
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
4

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

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

Community
  • 1
  • 1
em2
  • 93
  • 6
3

New method added by jQuery, the parents function allows you to check for all parents with selectors.

var ancestor = $(elem).parents(".myClass");

Sunny R Gupta
  • 5,026
  • 1
  • 31
  • 40
1

Try

var ancestor = $(elem).closest(selector what are you looking for);
bitoshi.n
  • 2,278
  • 1
  • 16
  • 16