Traversing Ancestors
In this page:
parent()
.parent() walks up exactly one level in the DOM tree and returns the immediate parent of each selected element. It never looks further up than one level, even if there's no match -- it simply won't skip ahead to a grandparent.
Example: parent()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="grandparent"><div id="parent"><p id="child">Text</p></div></div>
<script>
console.log($("#child").parent().attr("id"));
</script>
</body>
</html>
parents()
parents() selects all matching ancestors going all the way up to the document root, not just the immediate parent. You can optionally pass a selector to filter which ancestors in that whole chain get included.
Example: parents()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="grandparent"><div id="parent"><p id="child">Text</p></div></div>
<script>
console.log($("#child").parents().length);
</script>
</body>
</html>
parentsUntil()
parentsUntil() travels upward collecting ancestors, but stops just before reaching a chosen ancestor you specify, rather than going all the way to the root. This is useful when you know exactly where the walk should stop, like up to a specific container.
Example: parentsUntil()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="stop"><div id="mid"><p id="child">Text</p></div></div>
<script>
console.log($("#child").parentsUntil("#stop").length);
</script>
</body>
</html>
closest()
closest() finds the nearest matching ancestor starting from the element itself and moving upward, stopping at the very first match it finds. Unlike parents(), it stops as soon as it finds one match instead of collecting every ancestor that matches.
Example: closest()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div class="card"><p id="child">Text</p></div>
<script>
console.log($("#child").closest(".card").length);
</script>
</body>
</html>
Ancestor Practice
Ancestor methods are useful for changing a container based on a clicked or selected element inside it, such as finding the enclosing list item when a button inside it is clicked. closest() in particular is the standard tool for this in event-delegation patterns.
Example: Ancestor Practice
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<li class="task"><button id="del">Delete</button></li>
<script>
$("#del").on("click", function() {
$(this).closest(".task").remove();
});
</script>
</body>
</html>
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: