Let’s suppose to have the following html structure (1).
From $('.child') element I can access the $('.gran-parent') element making something like $('.child').parent().parent();.
Anyway I don’t think this is a good way because is not generic.
Let’s suppose there are other divs between $(‘.gran-parent’) and $(‘.child’).
What is the most generic way to refers to the first parent which class is gran-parent, starting from $('.child') ?
<div class='gran-parent'>
<div class='parent'>
<div class='child'>
</div>
</div>
</div>
You want:
.closestwill keep traversing up until it finds a.grand-parent. You can also do.parents(".grand-parent")but that could return more than one result, depending on your DOM hierarchy, so you would have to do:or:
or:
all of which are less elegant than
.closest().See: