JavaScript HTML DOM Collections

HTML DOM collections are objects that contain lists of DOM nodes or elements. These collections allow developers to access and manipulate groups of elements in a webpage using JavaScript. DOM collections are typically returned by methods like getElementsByTagName or getElementsByClassName.

Types of DOM Collections

DOM collections can include:

  • HTMLCollection
    • A live collection of HTML elements.Automatically updates if the DOM changes (e.g., elements are added or removed).Access elements by index or id/name attribute.
    Example:
const collection = document.getElementsByTagName("div");
console.log(collection[0]); // Access the first <div>
  • NodeList
    • A static or live list of nodes (depending on the method used).
    • Returned by methods like querySelectorAll (static) or childNodes (live).
    Example:
const list = document.querySelectorAll(".myClass");
console.log(list[0]); // Access the first element with class "myClass"

Key Differences: HTMLCollection vs. NodeList

FeatureHTMLCollectionNodeList
Type of ItemsContains only elements.Contains all nodes (elements, text, comments).
Live/StaticAlways live.Can be live or static.
Access MethodsAccess by index, id, or name.Access by index only.
IterationRequires a loop.Can use forEach (modern browsers).

Accessing DOM Collections

  • Using Index:
const items = document.getElementsByClassName("item");
console.log(items[0]); // First element with class "item"
  • Using Loops:
const items = document.getElementsByTagName("li");
for (let i = 0; i < items.length; i++) {
    console.log(items[i]); // Logs each <li> element
}
  • Using forEach (NodeList Only):
const items = document.querySelectorAll(".item");
items.forEach(item => {
    console.log(item); // Logs each element with class "item"
});

Common DOM Collection Methods

  • Length Property: Returns the number of elements in the collection.
const divs = document.getElementsByTagName("div");
console.log(divs.length); // Number of <div> elements
  • Access by id or name (HTMLCollection):
const forms = document.forms;
const formByName = forms["myForm"];
console.log(formByName); // Form element with name "myForm"
  • Iterating with Array.from(): Convert a collection to an array for modern array methods.
const items = Array.from(document.getElementsByClassName("item"));
items.map(item => console.log(item)); // Logs each element

Practical Applications of DOM Collections

  • Highlight All Elements:
const elements = document.getElementsByTagName("p");
for (const el of elements) {
    el.style.backgroundColor = "yellow";
}
  • Count Elements:
const buttons = document.getElementsByClassName("btn");
console.log(`There are ${buttons.length} buttons.`);
  • Modify Elements Dynamically:
const listItems = document.querySelectorAll("li");
listItems.forEach((item, index) => {
    item.textContent = `Item ${index + 1}`;
});

Best Practices

  1. Use Modern Methods When Possible:
    • Prefer querySelectorAll and forEach for better readability and flexibility.
  2. Avoid Overusing Live Collections:
    • Live collections can lead to performance issues if the DOM changes frequently.
  3. Convert to Arrays for Advanced Manipulation:
    • Use Array.from() or the spread operator ([...]) to work with DOM collections like arrays.

Conclusion

DOM collections are an essential part of interacting with web pages using JavaScript. Understanding their differences and how to work with them efficiently can help you manipulate the DOM effectively.

For more JavaScript tutorials, visit The Coding College.

Leave a Comment