jQuery select ancestor

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.

Leave a Comment