JavaScript DOM Traversing


DOM Traversing refers to the process of navigating the DOM tree using JavaScript. It allows you to move between parent, child, and sibling elements, enabling powerful and dynamic web page manipulation.



1. Accessing Parent Element

Use .parentElement to move from a child to its parent.

Example:

<div id="parent">
<p id="child">Hello</p>
</div>
<script>
const child = document.getElementById("child");
console.log(child.parentElement.id); // Output: "parent"
</script>


2. Accessing Children

Use .children or .firstElementChild / .lastElementChild.

Example:

<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<script>
const list = document.getElementById("list");
console.log(list.children); // HTMLCollection of <li>
console.log(list.firstElementChild); // <li>Item 1</li>
console.log(list.lastElementChild); // <li>Item 2</li>
</script>


3. Accessing Siblings

Use .previousElementSibling or .nextElementSibling.

Example:

<ul>
<li>Item 1</li>
<li id="middle">Item 2</li>
<li>Item 3</li>
</ul>
<script>
const middle = document.getElementById("middle");
console.log(middle.previousElementSibling.textContent); // Item 1
console.log(middle.nextElementSibling.textContent); // Item 3
</script>


4. childNodes vs. children

Property Returns
.children Only element nodes
.childNod es All node types (including text & comments)


Example:

const list = document.getElementById("list");
console.log(list.childNodes); // Might include text nodes (like
whitespace)
console.log(list.children); // Only actual <li> elements


5. Closest Ancestor Matching Selector

Use .closest() to find the nearest parent (or self) matching a selector.

Example:

<div class="card">
<p class="info">Click me</p>
</div>
<script>
const info = document.querySelector(".info");
const card = info.closest(".card");
console.log(card); // The outer <div class="card">
</script>


6. Traversing in Practice: Toggle Class of Parent Element

<div class="box">
<button onclick="highlightParent(this)">Highlight Box</button>
</div>
<script>
function highlightParent(btn) {
btn.parentElement.classList.toggle("highlight");
}
</script>
<style>
.highlight {
background-color: yellow;
}
</style>


Real-World Use Cases

  • Form validation by checking parent .form-group
  • Accordion toggles
  • Dynamic menus and dropdowns
  • Traversing nested structures like tables or cards