jQuery Traversing: Ancestors
An ancestor is any element above another in the tree: its parent, grandparent, and so on up to <html>. jQuery has four methods for going up.
| Method | Returns |
|---|---|
.parent(selector?) |
The direct parent of each element (optionally only if it matches) |
.parents(selector?) |
All ancestors, nearest first, up to <html> |
.parentsUntil(stop, filter?) |
Ancestors up to — but not including — the stop element |
.closest(selector) |
The first element matching selector, starting with the element itself |
parent() and parents()
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
div, ul, li, span { display: block; border: 2px solid #ccc; padding: 4px 8px; margin: 6px; color: #555; }
.hl { border-color: #e67e22; color: #e67e22; }
</style>
</head>
<body>
<div class="wrapper">div.wrapper
<ul>ul
<li>li
<span id="start">span#start</span>
</li>
</ul>
</div>
<button id="p1">parent()</button>
<button id="p2">parents()</button>
<button id="p3">parents("ul, div")</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const tags = $set => $set.map((i, el) => el.tagName.toLowerCase()).get().join(" → ");
function mark($set, label) {
$(".hl").removeClass("hl");
$set.addClass("hl");
console.log(label + ":", tags($set));
}
$("#p1").on("click", () => mark($("#start").parent(), "parent()"));
$("#p2").on("click", () => mark($("#start").parents(), "parents()"));
$("#p3").on("click", () => mark($("#start").parents("ul, div"), "parents(\"ul, div\")"));
</script>
</body>
</html>parents() without a filter returns li → ul → div → body → html — usually more than you want, which is why it is often combined with a selector.
parentsUntil()
.parentsUntil(stop) collects ancestors between the element and stop, excluding both. It is useful for highlighting a path inside a known container:
$("#start").parentsUntil(".wrapper"); // li, ulclosest(): the most useful one
.closest(selector) starts at the element itself, then walks up, and returns at most one element per starting element — the first match. That makes it perfect for event handlers: "which row/card/item was this click inside?"
.closest(sel) |
.parents(sel) |
|
|---|---|---|
| Starts at | The element itself | The parent |
| Returns | 0 or 1 element (per starting element) | 0 or more elements |
| Typical use | Find the containing component | Collect all matching ancestors |
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
table { border-collapse: collapse; width: 320px; }
td, th { border: 1px solid #ccc; padding: 4px 8px; }
tr.editing { background: #fff8d6; }
button { font-size: 12px; }
</style>
</head>
<body>
<table id="users">
<tr><th>Name</th><th>Role</th><th></th></tr>
<tr data-id="1"><td>Ana</td><td>Admin</td><td><button class="edit">Edit</button> <button class="del">Delete</button></td></tr>
<tr data-id="2"><td>Ben</td><td>Editor</td><td><button class="edit">Edit</button> <button class="del">Delete</button></td></tr>
<tr data-id="3"><td>Chloe</td><td>Viewer</td><td><button class="edit">Edit</button> <button class="del">Delete</button></td></tr>
</table>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$("#users").on("click", "button", function () {
const $row = $(this).closest("tr");
const id = $row.data("id");
const name = $row.children().first().text();
if ($(this).hasClass("del")) {
$row.fadeOut(200, function () { $(this).remove(); });
console.log("deleted user", id, name);
} else {
$row.toggleClass("editing").siblings().removeClass("editing");
console.log("editing user", id, name, "| inside table:", $row.closest("table").attr("id"));
}
});
</script>
</body>
</html>closest("tr") from a button returns that button's row, whichever row was clicked.
Guarding with closest()
Because .closest() includes the element itself, it is also a neat way to check "is this click inside some component?" — for example to close a popup when the user clicks outside it:
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; height: 240px; }
#pop { display: none; position: absolute; top: 50px; left: 20px; width: 220px; padding: 12px;
background: #fff; border: 1px solid #aaa; box-shadow: 0 6px 16px #0003; border-radius: 8px; }
</style>
</head>
<body>
<button id="open">Open popup</button>
<div id="pop">
<b>Popup</b>
<p>Clicks in here keep me open. Click outside to close.</p>
<input placeholder="try typing">
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$("#open").on("click", function () {
$("#pop").fadeIn(150);
});
$(document).on("click", function (e) {
const $t = $(e.target);
const inside = $t.closest("#pop, #open").length > 0;
console.log("clicked", e.target.tagName.toLowerCase(), "| inside popup or button:", inside);
if (!inside) $("#pop").fadeOut(150);
});
</script>
</body>
</html>$t.closest("#pop, #open").length is 1 if the click target is the popup, the button, or anything inside them — and 0 otherwise.
Note: The modern DOM has
element.closest(selector)built in, with the same behaviour. jQuery's version works on a whole set and returns a jQuery object.
Test yourself
What does $("#x").closest("div") return if #x is itself a <div>?
- Its parent div
#xitself- All div ancestors
- An empty set
Which method returns ALL ancestors of an element?
.parent().closest().parents().ancestors()
$("#start").parentsUntil(".wrapper") for div.wrapper > ul > li > span#start returns…
div.wrapper, ul, liul, li(asli,ul)span, li, ul- only
li