The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can manipulate the structure, style, and content. When working with JavaScript, understanding DOM Collections is essential for dynamic web development.
What Are DOM Collections?
DOM Collections are array-like objects that provide access to groups of elements in the DOM. Unlike traditional arrays, they are not strictly arrays but have similar properties, such as length and the ability to access elements using an index.
Types of DOM Collections
- HTMLCollection
- Represents a collection of HTML elements.
- Often returned by methods like
getElementsByTagName()
andgetElementsByClassName()
. - Live collection: updates automatically when the document changes.
let paragraphs = document.getElementsByTagName('p'); console.log(paragraphs.length); // Number of <p> tags in the document
- NodeList
- Represents a collection of nodes, which can include elements, text nodes, and comments.
- Returned by methods like
querySelectorAll()
andchildNodes
. - Can be live or static depending on the method used.
let divs = document.querySelectorAll('div'); divs.forEach(div => console.log(div.textContent)); // Logs text content of all <div> elements
Key Differences Between HTMLCollection and NodeList
| Feature | HTMLCollection | NodeList | |——————-|———————————|