How to Retrieve Ancestor Elements with jQuery parents()

This article explains how to retrieve all ancestor elements of a target DOM element using the jQuery parents() method. You will learn the basic syntax, see practical code examples for selecting all ancestors up to the document root, and discover how to apply optional selectors to filter specific ancestor elements efficiently.

Understanding the parents() Method

The parents() method in jQuery traverses up the DOM tree and returns all ancestor elements of the selected element, starting from its immediate parent all the way up to the root element (<html>). This differs from the parent() method, which only travels a single level up the DOM hierarchy.

Basic Syntax

$(selector).parents([filter]);
  • filter (optional): A string containing a selector expression to narrow down the retrieved ancestor elements.

Retrieving All Ancestors

To select every ancestor of an element without restriction, call parents() without any arguments.

HTML Structure

<div class="grandparent">
  <div class="parent">
    <p id="target">Child Element</p>
  </div>
</div>

jQuery Code

$(document).ready(function() {
  const ancestors = $("#target").parents();
  
  // Apply a style or inspect the retrieved elements
  ancestors.css("border", "1px solid red");
});

In this example, calling parents() on #target returns the <div class="parent">, <div class="grandparent">, <body>, and <html> elements.


Filtering Ancestor Elements

If you only need specific ancestors matching certain criteria (such as a specific class or tag name), pass a selector string as an argument.

jQuery Code

$(document).ready(function() {
  // Retrieve only ancestors that have the class "grandparent"
  const specificAncestor = $("#target").parents(".grandparent");
  
  specificAncestor.addClass("highlight");
});

This filters out all other ancestors, returning only elements that match .grandparent.


  • parent(): Returns only the direct parent element (one level up).
  • parents(): Returns all ancestors up to the root element, with optional filtering.
  • parentsUntil(): Returns all ancestors between the target element and a specified stop element.
  • closest(): Traverses up the DOM tree and returns the first single element that matches the selector, starting with the element itself.