Labs ICT
Pro Login

DOM Traversal

DOM Traversal

Once you have a reference to an element, you can move through the DOM tree to find related elements. This is called DOM traversal. Think of it like navigating a family tree — every element has parents, children, and siblings.

const list = document.querySelector("#myList");

// Get the parent element
const parent = list.parentElement;

// Get all direct children
const children = list.children;

// Get the first and last child
const first = list.firstElementChild;
const last = list.lastElementChild;

Sibling Navigation

Siblings are elements that share the same parent. You can move between them using nextElementSibling and previousElementSibling.

const currentItem = document.querySelector(".active");

// Move to the next sibling
const next = currentItem.nextElementSibling;

// Move to the previous sibling
const prev = currentItem.previousElementSibling;

// Get all siblings as an array
const siblings = Array.from(currentItem.parentElement.children);

Traversing Up the Tree

Sometimes you need to go upward from a child element to find a parent or ancestor. The closest() method is especially useful because it searches up the tree and stops at the first match.

const button = document.querySelector("button");

// Get the direct parent
const parentDiv = button.parentElement;

// Find the nearest ancestor with a specific class
const card = button.closest(".card");

// Walk up using parentNode (includes non-element nodes)
let current = button;
while (current && current.nodeType !== 1) {
  current = current.parentNode;
}
Try it Yourself →

Practical Example

Here is a common pattern: clicking a button inside a list item and finding which item was clicked.

document.querySelectorAll("button").forEach(button => {
  button.addEventListener("click", (e) => {
    // Find the closest list item ancestor
    const listItem = e.target.closest("li");
    console.log("Clicked item:", listItem.textContent);
  });
});

Summary

DOM traversal gives you the ability to navigate the element tree without going back to document.querySelector every time. Master parent, child, and sibling navigation to write cleaner, more efficient code.