</>
Skip to content
jQuery lessons (24/39)

jQuery — Ancestors

parent()

$("p").parent();            // Direct parent
$("p").parent(".container"); // Parent matching selector

parents()

$("p").parents();           // All ancestors
$("p").parents(".wrapper"); // Matching ancestors

closest()

$("span").closest("div");   // Closest ancestor div
$("span").closest("ul", ".sidebar"); // Stop at .sidebar

parentUntil()

Ancestors between two selectors:

$("li").parentUntil("ul");  // Stop at first ul

Practical: Event Delegation

// Using closest for event delegation
$("document").on("click", ".btn", function(e) {
    var $row = $(e.target).closest("tr");
    $row.addClass("selected");
});

Ancestor Traversal Methods

MethodDirectionStops At
parent()UpDirect parent
parents()UpAll ancestors
parentsUntil()UpUntil selector
closest()UpFirst match

Mini Practice

  1. Find the parent of a clicked element
  2. Use parents() to traverse up
  3. Use closest() to find a container
  4. Use parentUntil() to stop at a boundary

Up Next

Continue with Descendants — navigating down to child elements.

Related Topics

Frequently Asked Questions about Ancestors

What is Ancestors in jQuery?

Ancestors is a fundamental concept in jQuery. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Ancestors?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Ancestors.

Why is Ancestors important in jQuery?

Ancestors is essential for jQuery development. Understanding this concept will help you write better code and solve real-world problems more effectively.