DOM Navigation

Updated · 6 min read
mediumES2026javascriptdomtraversalclosest

DOM navigation (or traversal) means moving from one element to related elements: up to its parent, down to its children, or sideways to its siblings. You use it constantly in event handling: a Remove button was clicked, so find the row it belongs to; a checkbox changed, so find the form around it. Every node has properties for these relationships, in two versions: one that counts every node, including whitespace text, and one that counts only elements. The element versions, plus closest and matches, are what you'll use day to day.

In One Minute

  • Up: parentElement; to the nearest ancestor matching a selector: closest(selector).
  • Down: children, firstElementChild, lastElementChild, childElementCount.
  • Sideways: nextElementSibling, previousElementSibling.
  • Node versions (parentNode, childNodes, firstChild, nextSibling) include whitespace text nodes.
  • element.matches(selector) tests an element; element.contains(other) tests whether one is inside the other.

Element Navigation Properties

DirectionElement propertyNode property (includes text)
ParentparentElementparentNode
All childrenchildrenchildNodes
First childfirstElementChildfirstChild
Last childlastElementChildlastChild
Next siblingnextElementSiblingnextSibling
Previous siblingpreviousElementSiblingpreviousSibling
CountchildElementCountchildNodes.length
navigate.html
<ul id="fees">
  <li>Tuition</li>
  <li id="books">Books</li>
  <li>Lab</li>
</ul>
<script>
  const books = document.querySelector("#books");

  console.log(books.parentElement.id);
  console.log(books.previousElementSibling.textContent);
  console.log(books.nextElementSibling.textContent);
  console.log(books.parentElement.firstElementChild.textContent);
  console.log(books.parentElement.lastElementChild.textContent);
  console.log(books.parentElement.childElementCount);
  console.log(books.nextElementSibling.nextElementSibling);
</script>
Output
fees
Tuition
Lab
Tuition
Lab
3
null

When there is no such relative, the property is null: "Lab" has no next sibling.

Whitespace Text Nodes

The line breaks and spaces between tags in your HTML become text nodes in the DOM. The node-level properties see them:

whitespace.html
<ul id="fees">
  <li>Tuition</li>
  <li>Books</li>
</ul>
<script>
  const list = document.querySelector("#fees");
  console.log(list.childNodes.length, list.children.length);
  console.log(list.firstChild.nodeName, JSON.stringify(list.firstChild.textContent));
  console.log(list.firstElementChild.nodeName);
</script>
Output
5 2
#text "\n  "
LI

Explanation: the list has 5 child nodes (text, li, text, li, text) but only 2 child elements. firstChild is the line break and indentation before the first <li>. This is why code using firstChild or nextSibling often "finds nothing useful".

closest: Find the Nearest Ancestor

element.closest(selector) walks up from the element itself, through its parent, grandparent and so on, and returns the first one that matches the selector (or null). It is the standard way to get from a clicked button to its row or card:

closest.html
<table>
  <tr data-id="S-1"><td>Navika</td><td><button class="remove">Remove</button></td></tr>
  <tr data-id="S-2"><td>Advitha</td><td><button class="remove">Remove</button></td></tr>
</table>
<script>
  const button = document.querySelectorAll(".remove")[1];

  const row = button.closest("tr");
  console.log(row.dataset.id, row.cells[0].textContent);

  console.log(button.closest("table").tagName);
  console.log(button.closest("form"));
  console.log(button.closest(".remove") === button);
</script>
Output
S-2 Advitha
TABLE
null
true

closest starts with the element itself, which is why button.closest(".remove") returns the button. It returns null when no ancestor matches (there's no form here).

matches and contains

element.matches(selector) returns true if the element would be selected by the selector. a.contains(b) returns true if b is a or is inside it:

matches.html
<form id="pay">
  <input name="amount" type="number" required>
  <button type="submit" class="primary">Pay</button>
</form>
<button id="outside">Help</button>
<script>
  const amount = document.querySelector('[name="amount"]');
  const form = document.querySelector("#pay");

  console.log(amount.matches("input[required]"));
  console.log(amount.matches(":invalid"));
  console.log(form.contains(amount), form.contains(document.querySelector("#outside")));
  console.log(document.querySelector(".primary").matches("form > button"));
</script>
Output
true
true
true false
true

matches works with any selector, including states like :invalid (an empty required field) or :checked. Both methods are central to event delegation, where one listener on a parent decides what to do based on which child was clicked (see the event propagation lesson).

Walking the Tree

Navigation properties can walk any distance. This function collects every ancestor's tag name up to <html>:

ancestors.html
<main><section><article><p><strong id="here">Fee</strong></p></article></section></main>
<script>
  function ancestors(el) {
    const names = [];
    for (let node = el.parentElement; node; node = node.parentElement) {
      names.push(node.tagName.toLowerCase());
    }
    return names;
  }
  console.log(ancestors(document.querySelector("#here")).join(" < "));
</script>
Output
p < article < section < main < body < html

The loop stops when parentElement becomes null, above <html>. For walking large subtrees with filters, browsers also provide document.createTreeWalker, rarely needed in application code.

Collections Recap

Returned byLive?Has forEach
HTMLCollectionchildren, getElementsByClassName, table.rows, form.elementsYesNo
NodeListquerySelectorAll (static), childNodes (live)DependsYes

Both are array-like: they have length and numeric indexes, and work with for...of and spread, but don't have map or filter. Spread them into an array when you need array methods.

In Practice

The Fee Tracker's payment list handles clicks on any row's buttons with one listener on the table: closest finds which button and which row, and sibling navigation moves a row up:

delegation.html
<table><tbody id="rows">
  <tr data-id="1"><td>Navika</td><td><button class="up">Up</button><button class="remove">Remove</button></td></tr>
  <tr data-id="2"><td>Srihitha</td><td><button class="up">Up</button><button class="remove">Remove</button></td></tr>
  <tr data-id="3"><td>Advitha</td><td><button class="up">Up</button><button class="remove">Remove</button></td></tr>
</tbody></table>
<script>
  const rows = document.querySelector("#rows");
  const names = () => [...rows.rows].map((r) => r.cells[0].textContent).join(", ");

  rows.addEventListener("click", (event) => {
    const button = event.target.closest("button");
    if (!button) return;
    const row = button.closest("tr");
    if (button.matches(".remove")) row.remove();
    if (button.matches(".up") && row.previousElementSibling) row.previousElementSibling.before(row);
    console.log(names());
  });
</script>
Output
Navika, Advitha, Srihitha
Advitha, Srihitha

The checker clicked Up on the third row (Advitha moved above Srihitha), then Remove on the first row (Navika). One listener handles every current and future row.

Common Mistakes

Using firstChild or nextSibling and getting whitespace. Use firstElementChild and nextElementSibling.

Long chains like el.parentElement.parentElement.parentElement. They break when the markup changes. Use closest("tr").

Forgetting null at the ends. nextElementSibling of the last item is null. Check before using it.

Calling map on children. It's an HTMLCollection. Spread it first.

Practice

Challenge: Given a clicked "Pay" button inside a student card, log the student's name from the card's <h3>, using closest and querySelector.

Show solution
card.html
<div class="card" id="c1"><h3>Navika</h3><button class="pay">Pay</button></div>
<div class="card" id="c2"><h3>Srihitha</h3><button class="pay">Pay</button></div>
<script>
  document.addEventListener("click", (event) => {
    const button = event.target.closest(".pay");
    if (!button) return;
    console.log(button.closest(".card").querySelector("h3").textContent);
  });
</script>
Output
Srihitha

Quick check: DOM navigation

3 questions
1Which property skips whitespace text nodes?
2What does button.closest("tr") return?
3What does nextElementSibling return for the last child?

Key Takeaways

Go toProperty or method
Parentel.parentElement
Nearest matching ancestorel.closest(".card")
Childrenel.children
Next / previous elementel.nextElementSibling / el.previousElementSibling
Test a selectorel.matches(".remove")
Inside?parent.contains(el)

Was this tutorial helpful?

Lesson 71 of 139