HomeJAVASCRIPTHow to traverse the DOM?

How to traverse the DOM?

In JavaScript, traversing the DOM means moving through the DOM tree to access parent, child, and sibling elements relative to a given node.

Here are the main ways to traverse the DOM:


1. Parent Traversal

  • element.parentNode → Gets the parent node (can be an element, text, or document).
  • element.parentElement → Gets the parent element (only if it’s an element).
let child = document.querySelector(".child");
console.log(child.parentNode);     // parent node
console.log(child.parentElement);  // parent element

2. Child Traversal

  • element.childNodes → Returns all child nodes (including text and comments).
  • element.children → Returns only element children (HTMLCollection).
  • element.firstChild / element.lastChild → First/last node (could be text).
  • element.firstElementChild / element.lastElementChild → First/last element.
let parent = document.querySelector(".parent");
console.log(parent.children);              // only element children
console.log(parent.firstElementChild);     // first element child
console.log(parent.lastElementChild);      // last element child

3. Sibling Traversal

  • element.nextSibling / element.previousSibling → Any node.
  • element.nextElementSibling / element.previousElementSibling → Only element siblings.
let item = document.querySelector(".item");
console.log(item.nextElementSibling);     // next element sibling
console.log(item.previousElementSibling); // previous element sibling

4. Other Useful Traversals

  • element.closest(selector) → Finds the nearest ancestor that matches a selector.
  • element.querySelector(selector) → Finds the first matching descendant.
  • element.querySelectorAll(selector) → Finds all matching descendants.
let btn = document.querySelector(".btn");
console.log(btn.closest(".container")); // nearest ancestor with class "container"

Summary:

  • Up: parentNode, parentElement, closest()
  • Down: children, firstElementChild, lastElementChild, querySelector
  • Sideways: nextElementSibling, previousElementSibling

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *