← Back to all tutorials
JavaScriptEpisode 34

Traversing the DOM

Learn how to navigate between parent, child, and sibling elements in the DOM.

Traversing means navigating between elements in the DOM tree — moving to parents, children, and siblings.

Parent Elements

let item = document.querySelector("li");

item.parentElement;       // The <ul> or <ol>
item.parentNode;          // Usually the same as parentElement

Child Elements

let list = document.querySelector("ul");

list.children;            // All child elements (HTMLCollection)
list.firstElementChild;   // First child element
list.lastElementChild;    // Last child element
list.childElementCount;   // Number of children

Sibling Elements

let item = document.querySelector(".active");

item.nextElementSibling;     // Next sibling element
item.previousElementSibling; // Previous sibling element

Practical Example

// HTML:
// <ul id="menu">
//   <li>Home</li>
//   <li class="active">About</li>
//   <li>Contact</li>
// </ul>

let active = document.querySelector(".active");

console.log(active.textContent);                    // "About"
console.log(active.parentElement.id);               // "menu"
console.log(active.nextElementSibling.textContent);  // "Contact"
console.log(active.previousElementSibling.textContent); // "Home"

Walking the DOM

// Loop through all children of an element
let nav = document.querySelector("nav");

for (let child of nav.children) {
    console.log(child.tagName, child.textContent);
}

// Find a specific parent
let deepElement = document.querySelector(".deeply-nested");
let section = deepElement.closest("section"); // Finds nearest ancestor