jQuery select ancestor
ancestor, jquery, jquery-selectors
Solution
Try `parent()` for the immediate parent element.
$(".click-me").click(function() {
var ancestor = $(this).parent();
alert(ancestor)
});
Or `parents()` for all matching ancestor elements.
$(".click-me").click(function() {
var ancestors = $(this).parents(".some-ancestor");
alert(ancestors)
});
Or `closest()` for the first closest matching element (either an ancestor or self).
$(".click-me").click(function() {
var ancestor = $(this).closest(".some-ancestor");
alert(ancestor)
});
The difference between `parents()` and `closest()` is subtle but important. `closest()` will return the current element if it's a match; `parents()` returns only ancestors. You many not want the possibility of returning the current element. `closest()` also only returns one element; `parents()` returns all matching elements.
Problem
Is is possible to use jQuery to select an ancestor of an element? Markup: ``` <div id="ancestor-1"> <div> <a href="#" class="click-me">Click me</a> </div> </div> <div id="ancestor-2"> <div> <a href="#" class="click-me">Click me</a> </div> </div> ``` Script: ``` $(".click-me").click(function(){ // var ancestorId = ???; alert(ancestorId) }); ```