JavaScript DOM Collections

Subject: JavaScript

Types of DOM Collections

  1. HTMLCollection
  • Live collection of element nodes.
  • Updates automatically when the DOM changes.

Access via:

  • document.getElementsByTagName()
  • document.getElementsByClassName()

Example: HTMLCollection from Tags

  1. NodeList
  • Can be static or live depending on how retrieved.
  • Can contain any node types (elements, text, comments).

Access via:

  • document.querySelectorAll() (static)
  • childNodes (live, includes all node types)

Example: NodeList from Query Selector

Converting DOM Collections to Arrays

Key Takeaways

  • HTMLCollection is live and contains elements only.
  • NodeList can be static or live and may include all node types.
  • Use Array.from() to convert collections to arrays for array methods.
  • querySelectorAll() returns static NodeLists with forEach() support.