Finding an ancestor with a specific attribute or class in jQuery

I have a DOM element elemthat has an ancestor element that has a class myClass(alternatively an attribute with some name). The problem is that I need to easily find this ancestor using jQuery . I'm currently stuck in ugly trial errors like

var ancestor = $(elem).parent().parent().parent().parent().parent().parent().parent();

If the HTML code changes, jQuery code breaks easily.

Is it possible to find an ancestor element with more elegant jQuery code?

+5
source share
4 answers

Use closest(), it will move the DOM from the current element until it finds the parent element that matches the selector you provided.

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

Documents

+7
source

, jQuery, parents .

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

+2

Only a solution is presented class, but not attribute.

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

+2
source

Try

var ancestor = $(elem).closest(selector what are you looking for);
+1
source

All Articles