jQuery Traversing
Traversing means moving through the DOM tree relative to an element you already have: up to its parent, down to its children, sideways to its siblings. It is how event handlers find "the row this button belongs to" or "the panel after this header" without needing an id on everything.
The DOM as a family tree
<div class="card"> ← ancestor of everything below
<h3>Title</h3> ← child of div, sibling of ul and button
<ul> ← parent of the li elements
<li>One</li> ← descendant of div, sibling of the other li
<li>Two</li>
</ul>
<button>Buy</button>
</div>| Relationship | Meaning |
|---|---|
| Parent | The element directly above |
| Children | Elements directly below (one level) |
| Ancestors | Parent, grandparent, … up to <html> |
| Descendants | Children, grandchildren, … all the way down |
| Siblings | Elements with the same parent |
The traversal methods at a glance
| Direction | Methods | Lesson |
|---|---|---|
| Up | .parent(), .parents(), .parentsUntil(), .closest() |
Ancestors |
| Down | .children(), .find(), .contents() |
Descendants |
| Sideways | .siblings(), .next(), .nextAll(), .nextUntil(), .prev(), .prevAll(), .prevUntil() |
Siblings |
| Narrowing | .first(), .last(), .eq(), .filter(), .not(), .has(), .is() |
Filtering |
Every traversal method returns a new jQuery object, and most accept an optional selector to filter the result: .children("li"), .next(".panel").
Exploring the tree
Click any element inside the card. The script outlines it and its relatives in different colours and logs their tag names.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
.card { border: 1px solid #aaa; padding: 6px 12px; width: 280px; }
.card * { cursor: pointer; margin: 4px 0; }
.me { outline: 3px solid #e67e22; }
.parent { outline: 3px dashed #0769ad; }
.child { background: #d4edda; }
.sib { background: #fff3cd; }
</style>
</head>
<body>
<div class="card">
<h3>Coffee Grinder</h3>
<ul>
<li>Ceramic burrs</li>
<li>15 settings</li>
<li>Easy to clean</li>
</ul>
<p>Price: <b>$59</b></p>
</div>
<small>Orange = clicked, dashed blue = parent, green = children, yellow = siblings</small>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const names = $set => $set.map((i, el) => el.tagName.toLowerCase()).get();
$(".card").on("click", "*", function (e) {
e.stopPropagation();
$(".card, .card *").removeClass("me parent child sib");
const $me = $(this).addClass("me");
const $parent = $me.parent().addClass("parent");
const $kids = $me.children().addClass("child");
const $sibs = $me.siblings().addClass("sib");
console.log("clicked:", names($me), "| parent:", names($parent),
"| children:", names($kids), "| siblings:", names($sibs));
});
</script>
</body>
</html>Traversal in event handlers
The real power of traversing shows in handlers shared by many similar elements. Each button below finds its own card's data — there are no ids at all:
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
.product { display: inline-block; width: 120px; border: 1px solid #ccc; border-radius: 8px; padding: 8px; margin: 4px; vertical-align: top; }
.product.added { border-color: #2e7d32; background: #e8f5e9; }
.qty { font-weight: bold; }
</style>
</head>
<body>
<div class="product" data-price="3.5"><h4>Croissant</h4><button class="add">Add</button> <span class="qty">0</span></div>
<div class="product" data-price="2"><h4>Bagel</h4><button class="add">Add</button> <span class="qty">0</span></div>
<div class="product" data-price="4.25"><h4>Muffin</h4><button class="add">Add</button> <span class="qty">0</span></div>
<p>Total: lt;span id="total">0.00</span></p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(".add").on("click", function () {
const $card = $(this).closest(".product"); // up
const $qty = $(this).siblings(".qty"); // sideways
$qty.text(Number($qty.text()) + 1);
$card.addClass("added");
console.log("added", $card.find("h4").text()); // down
let total = 0;
$(".product").each(function () {
total += $(this).data("price") * Number($(this).find(".qty").text());
});
$("#total").text(total.toFixed(2));
});
</script>
</body>
</html>Iterating with each()
When you need to run custom code for every element in a set, use .each(). The callback receives the index and the DOM element; returning false stops the loop early.
$("li").each(function (index, element) {
console.log(index, $(element).text()); // `this` === element
if (index === 4) return false; // break
});| Method | Use it to |
|---|---|
.each(fn) |
Run code for each element (returns the original set) |
.map(fn).get() |
Turn each element into a value and collect a plain array |
.index() |
Get an element's position among its siblings |
.add(selector) |
Combine sets: $("h2").add("h3") |
Tip: Prefer specific traversals (
.closest(".product"),.siblings(".qty")) over long chains like.parent().parent().next(). Specific traversals keep working when someone adds a wrapper<div>to the HTML.
Test yourself
What is the difference between children and descendants?
- There is none
- Children are one level down; descendants are all levels down
- Descendants are one level down; children are all levels
- Children include text only
In a handler on many .add buttons, how do you find the .product card containing the clicked button?
$(".product")$(this).closest(".product")$(this).children(".product")$(this).next(".product")
How do you exit a jQuery .each() loop early?
breakreturn falsereturn truethis.stop()