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

Node vs Element Traversing

πŸ“Œ In the DOM, everything is a node

  • Element nodes β†’ <div>, <p>, <h1>

  • Text nodes β†’ spaces, line breaks, text inside elements

  • Comment nodes β†’ <!-- comment -->

πŸ‘‰ Whitespace also becomes a text node.

🌳 Sample HTML

<div id="box">
  <h2>Title</h2>
  <p>Paragraph</p>
</div>

⚠️ Notice the new lines and spaces β€” they matter.


πŸ”Ή 1. childNodes

βœ”οΈ What it does: Returns ALL child nodes of an element.

βœ”οΈ Includes

  • βœ… Text nodes (spaces, line breaks)

  • βœ… Element nodes

πŸ§ͺ Example

const box = document.getElementById("box");
console.log(box.childNodes);
NodeList(5)
0: text        ← newline
1: h2
2: text        ← newline
3: p
4: text        ← newline

πŸ“ Why?

Because childNodes follows the raw DOM tree, not just HTML tags.

πŸ”Ή 2. children

βœ”οΈ What it does: Returns ONLY element nodes.

❌ Does NOT include

  • Text nodes

  • Comments

πŸ§ͺ Example

console.log(box.children);
HTMLCollection(2) [h2, p]

πŸ“ Why?

This property is designed for clean element traversal, ignoring whitespace.

πŸ”Ή 3. firstChild

βœ”οΈ What it does: Returns the first node (not element) inside a parent.

⚠️ Important: It may return a text node!

πŸ§ͺ Example

console.log(box.firstChild);
#text

πŸ“ Why?

The first thing inside <div> is a newline, which becomes a text node.

πŸ”Ή 4. firstElementChild

βœ”οΈ What it does: Returns the first ELEMENT only.

πŸ§ͺ Example

console.log(box.firstElementChild);
<h2>Title</h2>

πŸ“ Why?

It skips text nodes and finds the first real HTML element.


🧠 Final Comparison Table

Property

What it Returns

Why

childNodes

Text + Elements

Raw DOM nodes

children

Only Elements

Cleaner traversal

firstChild

Text OR Element

First node (whitespace matters)

firstElementChild

Only Element

Ignores text nodes

βœ… Rule of Thumb (VERY IMPORTANT)

βœ”οΈ Use these in real projects:

children
firstElementChild
lastElementChild
nextElementSibling
previousElementSibling

❌ Avoid these unless needed:

childNodes
firstChild
lastChild

Property

Includes Text Nodes

Includes Elements

childNodes

βœ… Yes

βœ… Yes

children

❌ No

βœ… Yes

firstChild

βœ… Yes

❌ Maybe

firstElementChild

❌ No

βœ… Yes