Advance JavaScript (DOM, BOM, Web API) / Document Object Model

Traversing Elements

πŸ“Œ What is DOM Traversing?

DOM Traversing means moving through HTML elements relative to a selected element β€” such as moving to its parent, children, or siblings.

πŸ‘‰ Instead of selecting directly, you navigate the DOM tree.


🌳 Sample HTML (Used in All Examples)

<div id="container">
  <h2>Title</h2>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</div>

πŸ”Ό 1. parentElement

βœ”οΈ Purpose: Moves upward to get the parent element.

element.parentElement

πŸ§ͺ Example

const para = document.querySelector("p");
console.log(para.parentElement);
<div id="container">...</div

πŸ“ Explanation

  • Returns the direct parent element

  • Skips text and comment nodes

πŸ”½ 2. children

βœ”οΈ Purpose: Selects only element children of a parent.

element.children

πŸ§ͺ Example

const box = document.getElementById("container");
console.log(box.children);
HTMLCollection(3) [h2, p, p]

πŸ“ Explanation

  • Returns HTMLCollection

  • Does not include text nodes (spaces, line breaks)

πŸ”½ 3. firstElementChild

βœ”οΈ Purpose: Selects the first child element.

element.firstElementChild

πŸ§ͺ Example

const box = document.getElementById("container");
console.log(box.firstElementChild.textContent);
Title

πŸ“ Explanation

  • Skips text nodes

  • Useful when structure is known

➑️ 4. nextElementSibling

βœ”οΈ Purpose: Moves to the next sibling element.

element.nextElementSibling

πŸ§ͺ Example

const firstPara = document.querySelector("p");
console.log(firstPara.nextElementSibling.textContent);
Paragraph 2

πŸ“ Explanation

  • Ignores text nodes

  • Returns null if no sibling exists

πŸ”½ 5. lastElementChild

βœ”οΈ Purpose: Selects the last child element.

element.lastElementChild

πŸ§ͺ Example

console.log(box.lastElementChild.textContent);
Paragraph 2

⬅️ 6. previousElementSibling

βœ”οΈ Purpose: Moves to the previous sibling element.

element.previousElementSibling

πŸ§ͺ Example

const secondPara = document.querySelectorAll("p")[1];
console.log(secondPara.previousElementSibling.textContent);
Paragraph 1


🎯 Real-World Use Case

// Highlight all children
Array.from(box.children).forEach(child => {
  child.style.border = "1px solid blue";
});

// Move from one element to another
document.querySelector("h2")
  .nextElementSibling
  .style.color = "red";