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
| Method | Direction | Stops At |
|---|---|---|
| parent() | Up | Direct parent |
| parents() | Up | All ancestors |
| parentsUntil() | Up | Until selector |
| closest() | Up | First match |
Mini Practice
- Find the parent of a clicked element
- Use parents() to traverse up
- Use closest() to find a container
- 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.