HomeJAVASCRIPTDifference between HTMLCollection and NodeList.

Difference between HTMLCollection and NodeList.

πŸ‘ Let’s break down the difference between HTMLCollection and NodeList in JavaScript DOM:


1. What they are

  • HTMLCollection β†’ A live collection of HTML elements only.
  • NodeList β†’ A collection of nodes (can be elements, text nodes, comments, etc.).

2. Live vs Static

  • HTMLCollection is live β†’ It updates automatically when the DOM changes.
  • NodeList can be live or static:
    • Returned by querySelectorAll() β†’ static (doesn’t update if DOM changes).
    • Returned by childNodes β†’ live (updates with DOM changes).

3. Methods available

  • HTMLCollection
    • Indexed like an array (can access by index).
    • Can be accessed by name, id, or index.
    • ❌ No built-in forEach().
  • NodeList
    • Indexed like an array.
    • βœ… forEach() is available (on modern browsers).
    • ❌ No map, filter, reduce (must convert to array first).

4. How they are obtained

  • HTMLCollection comes from:
    • document.getElementsByTagName()
    • document.getElementsByClassName()
    • document.forms, document.images, etc.
  • NodeList comes from:
    • document.querySelectorAll() (static)
    • node.childNodes (live)

5. Example

<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

<script>
  let htmlCollection = document.getElementsByTagName("li"); // HTMLCollection (live)
  let nodeList = document.querySelectorAll("li"); // NodeList (static)

  console.log(htmlCollection); // HTMLCollection(2)
  console.log(nodeList);       // NodeList(2)

  // Add a new li
  let newLi = document.createElement("li");
  newLi.textContent = "Item 3";
  document.getElementById("list").appendChild(newLi);

  console.log(htmlCollection.length); // 3 (live update)
  console.log(nodeList.length);       // 2 (static, no update)
</script>

βœ… Summary Table:

FeatureHTMLCollectionNodeList
ContainsOnly HTML elementsAny node (elements, text, etc.)
Live or StaticAlways liveCan be live or static
Common sourcesgetElementsBy*querySelectorAll, childNodes
MethodsNo forEachHas forEach (modern browsers)
Array methods❌ Not available❌ Not available (convert first)

Share:Β 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *