🌳 DOM Traversing

Last Updated: 26th October 2025


  • DOM Traversing means navigating through the HTML elements (nodes) in the DOM tree.
  • Helps us select, access, and manipulate elements relative to other elements.

Hinglish Tip 🗣: Jaise tree me branches aur leaves hote hain, DOM me elements parent-child-sibling relationship me hote hain. Traversing se hum kisi branch se dusre branch par ja sakte hain.


Parent Node / Parent Element

<div id="parent">
  <p id="child">Hello World</p>
</div>

<script>
  const child = document.getElementById("child");
  console.log(child.parentNode); // <div id="parent">
  console.log(child.parentElement); // <div id="parent">
</script>
  • parentNode & parentElement often return the same element.
  • parentNode can also return Document for topmost node.

Child Nodes / Children

<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<script>
  const list = document.getElementById("list");
  console.log(list.childNodes); // NodeList including text nodes
  console.log(list.children); // HTMLCollection of <li> elements only
</script>
  • childNodes → includes all nodes (text, comments, elements)
  • children → includes only element nodes

First & Last Child

console.log(list.firstChild); // Might include text node (whitespace)
console.log(list.firstElementChild); // First <li> element

console.log(list.lastChild);
console.log(list.lastElementChild);
  • firstChild & firstElementChild → includes text node
  • lastChild & lastElementChild → includes text node

Sibling Elements

const item2 = list.children[1];

console.log(item2.previousSibling); // Could be text node
console.log(item2.previousElementSibling); // <li>Item 1</li>

console.log(item2.nextSibling); // Could be text node
console.log(item2.nextElementSibling); // <li>Item 3</li>
  • previousElementSibling & nextElementSibling → only elements
  • previousSibling & nextSibling → any node type

💡 Quick Practice

  • Get the parent of a paragraph and change its background color.
  • Access the first and last item of a list and make them bold.
  • Loop through all children of a div and append "!" to their text.
  • Select the next sibling of an element and hide it using CSS.