JAVASCRIPT

How to traverse the DOM?

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
No comments yet! You be the first to comment.

Leave a Reply

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