Script Valley
JavaScript in the Browser: DOM, Events & APIs
Understanding the DOMLesson 1.4

How to traverse the DOM tree with parent, child, and sibling properties

parentElement, children, firstElementChild, lastElementChild, nextElementSibling, previousElementSibling, closest

Traversing the DOM Tree

Traversal properties let you navigate the tree relative to a known node โ€” useful when you cannot predict exact IDs or classes.

Moving Up and Down

const item = document.querySelector('.active');

// Go up
console.log(item.parentElement);

// Go down
console.log(item.children);          // HTMLCollection of child elements
console.log(item.firstElementChild);
console.log(item.lastElementChild);

Moving Sideways

console.log(item.nextElementSibling);
console.log(item.previousElementSibling);

closest() โ€” Walk Up Until Match

closest(selector) starts at the current element and walks up the tree, returning the first ancestor that matches the selector โ€” or null if none found. It is the cleanest way to find a containing component from a deeply nested click target.

// User clicks a button inside a .card div
document.querySelector('button').addEventListener('click', function(e) {
  const card = e.target.closest('.card');
  card.classList.add('selected');
});

Prefer closest over manual parentElement chains. It is shorter, more readable, and does not break if you add nesting layers later.

Up next

Creating and inserting DOM elements dynamically with JavaScript

Sign in to track progress

How to traverse the DOM tree with parent, child, and sibling properties โ€” Understanding the DOM โ€” JavaScript in the Browser: DOM, Events & APIs โ€” Script Valley โ€” Script Valley