Understanding Node, Element, NodeList, and HTMLCollection in the DOM
This article explains the differences between Node and Element in the DOM, clarifies the roles of NodeList and HTMLCollection, demonstrates how to inspect child nodes with code examples, and provides practical tips for handling these objects in frontend development.
Introduction
We often use document.getElementById to obtain elements and childNodes to retrieve child nodes. What is the difference between Element and Node, and what are HTMLCollection, HTMLElement, and NodeList?
A simple page
<code><html>
<body>
<h1>China</h1>
<!-- My comment ... -->
<p>China is a popular country with...</p>
<div>
<button>See details</button>
</div>
</body>
</html>
</code>The body has three direct child elements: h1 , p , and div . Using document.body.childNodes shows the result, which includes text nodes and comment nodes.
Questions: Why are there many #text nodes? Do comments count as nodes?
Node vs Element
A Node is an interface from which many DOM types inherit, allowing them to be treated similarly. Interfaces inheriting from Node include Document, Element, CharacterData (Text, Comment, CDATASection), ProcessingInstruction, DocumentFragment, DocumentType, Notation, Entity, and EntityReference.
In short, Node is a base class; Element, Text, and Comment inherit from it. These correspond to ELEMENT_NODE , TEXT_NODE , and COMMENT_NODE types.
Therefore, the HTML elements we use are Elements, which are Nodes of type ELEMENT_NODE . The nodeType property can be used to inspect these types.
NodeList vs HTMLCollection
Using childNodes returns a NodeList . When we want to work only with element nodes, we use methods like getElementsByTagName which return an HTMLCollection (also called ElementCollection).
Both NodeList and HTMLCollection are array‑like objects, not true arrays; they can be converted to real arrays with Array.from() .
Conclusion
The Document Object Model (DOM) provides a programming interface for HTML and XML documents, representing them as a tree structure whose root is the document object. Understanding Nodes, Elements, NodeLists, and HTMLCollections is essential for effective frontend development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.