Walking With Dom In Js

Posted on March 12, 2025 by Vishesh Namdev
Python C C++ Javascript Java
DOM Tree in JS

Walking with DOM
Walking the DOM (Document Object Model) means navigating through elements, nodes, and their relationships in a webpage using JavaScript. The DOM is structured like a tree, where elements are nodes connected in a hierarchical manner:

DOM tree in JS

Accessing Root Nodes

 console.log(document.documentElement); // Entire  element
  console.log(document.head); //  element
  console.log(document.body); //  element

Navigating Parent, Child, and Sibling Nodes

 console.log(document.documentElement); // Entire  element
      console.log(document.head); //  element
      console.log(document.body); //  element

Sibling Nodes (previousSibling, nextSibling)

 let heading = document.querySelector("h1");
  console.log(heading.nextSibling);  // Next node (can be text)
  console.log(heading.previousSibling); // Previous node
  console.log(heading.nextElementSibling); // Next element sibling
  console.log(heading.previousElementSibling); // Previous element sibling

Using Loops for DOM Traversal

 let listItems = document.querySelectorAll("li");

    listItems.forEach(item => {
        console.log(item.innerText);
    });
📢Important Note📢