childNodes vs children
What you'll learn: You'll understand the difference between two ways of accessing an element's descendants — and why one gives you everything while the other only gives you elements.
The Core Difference
When you access a parent element's children in the DOM, you have two main options: childNodes and children. They sound similar, but return very different things:
childNodesreturns a live NodeList containing all child nodes — including elements, text nodes (even whitespace!), and comments.childrenreturns a live HTMLCollection containing only element nodes — no text, no comments, just actual HTML elements.
Why This Matters
Imagine a <div> with this structure:
<div id="parent">
<p>Hello</p>
<span>World</span>
</div>
If you check parent.childNodes, you might get 5 nodes: a text node (whitespace), the <p> element, another text node (whitespace), the <span> element, and a final text node. That's because browsers preserve whitespace between tags as text nodes.
But parent.children returns exactly 2: just the <p> and <span> elements.
When to Use Each
Use children when you want to loop through or manipulate only the HTML elements inside a parent — this is the most common scenario.
Use childNodes when you need access to text nodes or comments, or when you're working at a lower level with the DOM structure.
The Collections Are Live
Remember: both return live collections. If you add or remove child elements, both childNodes and children automatically update to reflect the current state.
Key Takeaway: Use children for element-only access (cleaner, more predictable), and childNodes only when you need all node types including text and comments.