Module 35 : DOM Traversal
🧠 Section 1: What is DOM Traversal?
✅ Definition:
DOM Traversal refers to the process of navigating through the DOM tree using JavaScript to access or manipulate nodes (elements, text, attributes).
The DOM is a hierarchical tree where each element (HTML tag) is a node. Traversal helps you go:
Upwards (to parent elements)
Downwards (to children)
Sideways (to siblings)
Section 2: Common DOM Traversal Methods
🔹 1. parentNode / parentElement
Returns the parent node of the current element.
js code
const child = document.getElementById("myPara"); console.log(child.parentNode); // Logs the parent element
🔹 2. children
Returns a live HTMLCollection of child elements (excluding text nodes, comments).
js code
const container = document.getElementById("main"); console.log(container.children); // Returns child elements
🔹 3. firstElementChild / lastElementChild
Access the first or last child element.
js code
console.log(container.firstElementChild); // First child console.log(container.lastElementChild); // Last child
🔹 4. nextElementSibling / previousElementSibling
Navigate to the next or previous sibling element.
js code
const current = document.getElementById("item1"); console.log(current.nextElementSibling); // Gets next sibling
🔹 5. childNodes
Returns all child nodes (including text, comment, element nodes).
js code
console.log(container.childNodes); // May include text nodes
💡 Section 3: Examples
🌐 Example HTML:
html code
<div id="container"> <h2>Title</h2> <p id="para1">First paragraph</p> <p id="para2">Second paragraph</p> </div>
📘 Example JavaScript:
js code
const para1 = document.getElementById("para1"); console.log(para1.parentNode); // <div id="container"> console.log(para1.nextElementSibling); // <p id="para2"> console.log(para1.previousElementSibling); // <h2>Title console.log(para1.parentNode.children); // All children of #container
🔍 Explanation:
para1.parentNode: Moves up to the container <div>
nextElementSibling: Moves sideways to the next <p>
previousElementSibling: Gets the <h2> before <p>
children: Lists all direct children of container
Section 4: Objective:
Manipulate a list using DOM traversal. Change the background color of the second list item using traversal methods only.
HTML Setup:
html code
<ul id="fruits"> <li>Apple</li> <li>Banana</li> <li>Mango</li> </ul>
Write JavaScript to access the second <li> (Banana) and change its background color to yellow.
JavaScript Code:
js code
const ul = document.getElementById("fruits"); const secondItem = ul.children[1]; secondItem.style.backgroundColor = "yellow";
🧠 Explanation:
ul.children gives a list of <li> elements
[1] accesses the second item (indexing starts at 0)
We then style it dynamically
Goal
🎯 Access the last list item using firstElementChild and nextElementSibling.
js code
const first = ul.firstElementChild; const second = first.nextElementSibling; const third = second.nextElementSibling; third.style.color = "green";
📚 Section 5: Research-Based Insights
🔎 Best Practices in DOM Traversal:
Practice
Why It Matters
Prefer children over childNodes
More consistent—ignores text nodes
Avoid excessive traversal
Can reduce performance
Cache traversed elements
Avoid repeated DOM calls in loops
Use semantic IDs/classes
Makes traversal more readable and maintainable
🧠 Insight:
According to performance benchmarks from Mozilla and Google DevTools:
getElementById and children[n] are faster than query selectors
Avoid DOM reflow/repaint by minimizing manipulation during traversal
📄 Citation:
Mozilla Developer Network (MDN): https://developer.mozilla.org/en-US/docs/Web/API/Node
Google Web Fundamentals
Section 6:
Exercises
✅ Exercise 1:
Using only DOM traversal, access and log the second paragraph in the following HTML:
html code
<div id="textBlock"> <p>Intro</p> <p>Main Content</p> <p>Conclusion</p> </div>
✔️ Expected: Main Content
js code
const div = document.getElementById("textBlock"); console.log(div.children[1].innerText);
✅ Exercise 2:
Use previousElementSibling to find the sibling before a paragraph with id "p3".
html code
<p id="p1">One</p> <p id="p2">Two</p> <p id="p3">Three</p>
js code
const p3 = document.getElementById("p3"); console.log(p3.previousElementSibling.innerText); // Output: Two
🧠 Section 7: Summary
DOM traversal is crucial for interacting with web pages dynamically
Use parentNode, children, and sibling methods for effective navigation
Avoid relying on complex selectors when direct traversal is available
Practical use cases include dynamically changing content, validating input sections, or manipulating lists
Assignment
💡 Write a function highlightLastItem() that highlights the last item in a list with id "myList".
html code
<ul id="myList"> <li>One</li> <li>Two</li> <li>Three</li> </ul>
✅ Expected Output:
The last <li> (Three) gets a red background.
💻 Code:
js code
function highlightLastItem() { const list = document.getElementById("myList"); const last = list.lastElementChild; last.style.backgroundColor = "red"; } highlightLastItem();
📖 Reading:
MDN Traversing the DOM
JavaScript.info DOM Navigation
DOM Navigation
No comments:
Post a Comment