How to search for a parent element that contains a specific selector

Suppose it has the following html (1) structure.
From the $('.child') element I can access the $('.gran-parent') element , something like $('.child').parent().parent(); .

In any case, I do not think that this is a good way, because it is not general.
Suppose there are other divs between $ ('. Gran-parent') and $ ('. Child').
What is the most common way to access the first parent whose class is gran-parent , starting with $('.child') ?

 <div class='gran-parent'> <div class='parent'> <div class='child'> </div> </div> </div> 
+4
source share
2 answers

Do you want to:

 $('.child').closest(".grand-parent"); 

.closest will continue to move until it finds .grand-parent . You can also do .parents(".grand-parent") , but this can produce several results, depending on your DOM hierarchy, so you will need to:

 .parents(".grand-parent").eq(0) 

or

 .parents(".grand-parent").slice(0) 

or

 .parents(".grand-parent:first") 

all of which are less elegant than .closest() .

Cm:

+5
source

You are looking for an operator . parents () .

Example:

 $('.child').parents('.gran-parent'); 
+2
source

All Articles