In the Document Object Model (DOM), a DOM collection is a special type of object that represents a list or collection of DOM nodes. DOM collections are typically returned by various DOM methods when you query for multiple elements that match a specific criteria, such as elements with a certain tag name, class name, or attributes.
DOM collections are not standard JavaScript arrays, but they behave similarly and have some array-like properties, such as the `length` property and numeric indexing. However, they do not have all the methods available on regular arrays (e.g., `forEach`, `map`, etc.).
Here are some common DOM collections:
1. **NodeList**:
The most common DOM collection is a `NodeList`, which is returned by methods like `querySelectorAll` and `getElementsByTagName`. It represents a collection of nodes, including elements, text nodes, and comment nodes.
javascript
const paragraphs = document.querySelectorAll('p');
// Accessing elements in a NodeList
const firstParagraph = paragraphs[0];
const secondParagraph = paragraphs[1];
2. **HTMLCollection**:
Another type of DOM collection is an `HTMLCollection`, which is returned by properties like `children`, `getElementsByTagName`, `getElementsByClassName`, etc. It represents a collection of elements only.
javascript
const parentElement = document.getElementById('parent');
const children = parentElement.children;
// Accessing elements in an HTMLCollection
const firstChild = children[0];
const secondChild = children[1];
3. **Other Collections**:
Depending on the DOM method you use, you might encounter other specialized collections, like `NamedNodeMap` for attributes of an element.
DOM collections are live, which means they are automatically updated when the DOM changes. If you add or remove elements that match the original query, the NodeList or HTMLCollection will reflect those changes without needing to be re-queried.
However, since DOM collections are not regular JavaScript arrays, you cannot directly use array methods on them. If you want to use array methods on a DOM collection, you can convert it to a standard array using techniques like spread syntax or `Array.from`.
javascript
const paragraphs = document.querySelectorAll('p');
const paragraphArray = [...paragraphs]; // Convert NodeList to array
paragraphArray.forEach((paragraph) => {
console.log(paragraph.textContent);
});
Keep in mind that DOM collections are relatively simple data structures, and you may prefer to use more robust array manipulation features provided by standard JavaScript arrays if you need more advanced operations.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc