Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 56 ยท Traversing the DOM

Traversing Up the Tree

Move from an element to its ancestors with jQuery .parent(), .parents(), .parentsUntil(), .closest() and .offsetParent(), plus patterns for event targets.

A page is a tree. Every element sits inside a parent, which sits inside its own parent, all the way up to <html>. Often you start from one element, such as the button that was clicked, and need something around it: the card it belongs to, the form it is in, the row of a table. Moving up the tree is called traversing, and jQuery gives you five methods for it.

Unlike selectors, which search the whole document from the outside, traversal starts from elements you already have and walks the structure. That makes your code robust and reusable: a click handler that finds "the card around me" works for every card on the page, with no ids or counters.

Five ways up

parent Exactly one level up.
parents Every ancestor, nearest first.
parentsUntil Ancestors up to, not including, a stop.
closest Nearest ancestor that matches, including itself.
1 / 2

A tree to practice on

All the examples use this markup:

HTML
<div id="shop" class="store">
  <section class="card" id="card-1">
    <h3>Lamp</h3>
    <p><span class="price"><b>$20</b></span></p>
  </section>
</div>

Starting from b (the bold price), the ancestors in order are: span.price, p, section.card, div#shop, body, html.

.parent(): one level up

.parent() returns the direct parent of each element. You can pass a selector to keep only the parents that match.

JavaScript
$("b").parent();              // span.price
$("b").parent("p");           // empty: the parent is a span, not a p

If the set has several elements, you get one parent each, with duplicates removed. Three <li> children of the same <ul> give a set with just that one <ul>.

.parents(): all ancestors

.parents() returns every ancestor, ordered from the closest to the outermost, all the way to html. An optional selector filters the list.

JavaScript
$("b").parents();                 // span, p, section, div, body, html
$("b").parents(".card");          // section.card
$("b").parents("[id]").first();   // nearest ancestor that has an id

Note that .parents() never includes the starting element and it always goes to the very top. Without a selector it often returns far more than you need.

.parentsUntil(): stop before a boundary

.parentsUntil(selector) returns the ancestors up to, but not including, the first one that matches the selector. It is useful when you want everything inside some container.

JavaScript
$("b").parentsUntil(".card");     // span.price and p
$("b").parentsUntil(".card", "p"); // only the p, filtered by second argument
$("b").parentsUntil();            // with no argument, behaves like .parents()

.closest(): the nearest match

.closest(selector) starts at the element itself, then checks its parent, then its grandparent, and so on. It stops at the first element that matches and returns just that one.

JavaScript
$("b").closest(".card");      // section.card
$("b").closest("b");          // the b itself, because it matches first
$("b").closest(".nothing");   // empty set

Two differences from .parents(selector) matter in practice. First, .closest() includes the starting element. Second, it returns at most one element per starting element, while .parents() returns all matches. When you mean "the card I am in", .closest(".card") is the right call, even if cards are nested, because it picks the innermost.

Try all four on the same tree. Click a button and see which elements are highlighted.

parent, parents, parentsUntil and closest

.offsetParent(): for coordinates

.offsetParent() returns the nearest ancestor that is positioned, meaning its CSS position is relative, absolute, fixed or sticky. If none exists it returns the html element. This is the element against which an absolutely positioned child is measured, so it matters when you compute coordinates with .position(). You will rarely call it directly, but it explains why a tooltip lands in the wrong place when you forgot position: relative on its wrapper.

Patterns for event targets

Traversal shines inside event handlers. When one handler serves many items, you need to find the item that belongs to the clicked control. The pattern is always the same: start at this (or event.target), go up with .closest(), then work inside the result with .find().

JavaScript
$("#shop").on("click", ".remove", function () {
  const $card = $(this).closest(".card");   // the card around this button
  $card.fadeOut(200, function () { $(this).remove(); });
});

Prefer .closest() over chains such as .parent().parent(). A chain breaks the moment someone adds a wrapper element, whereas .closest(".card") keeps working. This is also the heart of event delegation, where event.target may be a tiny element deep inside the item you care about.

A delegated handler that finds its card

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method includes the starting element in its search?

    .closest() tests the element itself first, then climbs. The other three only look at ancestors.
  2. 2. Given b inside span inside p inside section.card, what does $('b').parentsUntil('.card') return?

    parentsUntil stops before the matching ancestor, so section.card is excluded.
  3. 3. Why is .closest('.card') safer than .parent().parent() in a click handler?

    Counting levels bakes the exact markup into the code. A selector describes what you want, not how far away it is.
  4. 4. What does .offsetParent() return?

    It finds the nearest positioned ancestor (or html), the box that absolutely positioned descendants are measured from.

Summary

  • .parent() goes one level up; .parents() returns all ancestors, nearest first; .parentsUntil(sel) stops before the match.
  • .closest(sel) starts at the element itself and returns the nearest matching element, at most one per starting element.
  • All of them accept an optional selector to filter their result.
  • .offsetParent() finds the nearest positioned ancestor and matters for coordinate math.
  • In handlers, start at this, climb with .closest(), then dive back down with .find().
  • Avoid chains like .parent().parent(); they break when markup changes.

Next: Traversing Down and Sideways covers children, descendants and siblings.