JS DOM Navigation

DOM navigation allows you to traverse elements in the document tree. Access parents, children, and siblings easily.

On this page

DOM Navigation

DOM navigation allows you to move between elements in the document tree. Every HTML page is represented as a tree of nodes.

const parent = document.querySelector("#parent");
console.log(parent.children);

Common navigation properties:

  • parentNode / parentElement
  • childNodes / children
  • firstChild / firstElementChild
  • lastChild / lastElementChild
  • nextSibling / nextElementSibling
  • previousSibling / previousElementSibling

DOM Nodes

Everything in the DOM is a node: elements, text, comments.

const el = document.querySelector("#demo");

console.log(el.nodeName);
console.log(el.nodeType);
console.log(el.nodeValue);

Common node types:

  • 1 = Element node
  • 3 = Text node
  • 8 = Comment node

Difference between childNodes and children:

const container = document.querySelector("#container");

console.log(container.childNodes); // includes text nodes
console.log(container.children);   // only element nodes

DOM Collections

Some DOM methods return HTMLCollection objects. These are live collections — they update automatically when the DOM changes.

const items = document.getElementsByClassName("item");

console.log(items.length);

// If you add a new element with class "item", this collection updates automatically.

HTMLCollection is array-like but not a real array.

Array.from(items).forEach(el => {
  console.log(el.textContent);
});

DOM Node Lists

querySelectorAll() returns a NodeList. Unlike HTMLCollection, it is usually static (does not auto-update).

const nodes = document.querySelectorAll(".item");

console.log(nodes.length);

nodes.forEach(el => {
  console.log(el.textContent);
});

Live vs static difference:

const live = document.getElementsByTagName("li");  // live
const staticList = document.querySelectorAll("li"); // static

Modern tip: prefer querySelector and querySelectorAll for flexibility and consistency.

Traversing Example

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

const first = list.firstElementChild;
const next = first.nextElementSibling;

console.log(first.textContent);
console.log(next.textContent);

Best Practices

  • Prefer children over childNodes when you only need elements.
  • Convert collections using Array.from() when needed.
  • Avoid deep traversal in performance-critical loops.

Next Step

Continue with JS Web APIs or JS Windows for more browser-level functionality.

JS DOM Navigation Examples (8)