How to look for a parent element which contains a specific selector
javascript, jquery, jquery-selectors
Solution
You want:
$('.child').closest(".grand-parent");
`.closest` will 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:
.parents(".grand-parent").eq(0)
or:
.parents(".grand-parent").slice(0)
or:
.parents(".grand-parent:first")
all of which are less elegant than `.closest()`.
See:
- http://api.jquery.com/closest/
- http://api.jquery.com/parents/
Problem
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> ```