Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Dom Collections in JavaScript

Dom Collections in JavaScript

? DOM Collections in JavaScript


What Are DOM Collections?

DOM Collections are array-like objects returned by various DOM methods that represent groups of elements or nodes in a document. Unlike regular arrays, they often have limited methods but can be iterated similarly.


Common DOM Collections

Collection TypeReturned ByDescription
HTMLCollectiondocument.getElementsByTagName(), document.getElementsByClassName(), element.childrenLive collection of elements matching criteria
NodeListdocument.querySelectorAll(), childNodesStatic (or live in some cases) list of nodes
NamedNodeMapelement.attributesCollection of attributes of an element

1. HTMLCollection

  • Live collection — updates automatically when the DOM changes

  • Contains only element nodes (no text or comment nodes)

  • Common methods: .item(index), .namedItem(name), and can be accessed by index [0]

const divs = document.getElementsByTagName("div");console.log(divs.length);console.log(divs[0].innerText);

2. NodeList

  • Can be static or live (most modern ones like querySelectorAll are static)

  • Contains any type of node (elements, text, comments)

  • Has .forEach() method, but not all Array methods

  • Can be converted to an array using Array.from() or spread [...nodeList]

const nodes = document.querySelectorAll(".item");nodes.forEach(node => {  console.log(node.textContent);});

3. NamedNodeMap

  • Collection of attributes of an element

  • Access by index or attribute name

const attrs = document.querySelector("img").attributes;console.log(attrs.length);console.log(attrs["src"].value);

Differences Summary

FeatureHTMLCollectionNodeList
Live vs StaticLiveUsually static (except childNodes)
ContainsElements onlyAny node type
MethodsLimitedHas .forEach()
ConversionCan be converted to ArrayCan be converted to Array

Example: Looping Through a Collection

const elements = document.getElementsByClassName("box");// Using for loop (works for both HTMLCollection and NodeList)for (let i = 0; i < elements.length; i++) {  elements[i].style.backgroundColor = "lightblue";}// Using forEach (works only on NodeList)const nodeList = document.querySelectorAll(".box");nodeList.forEach(el => el.style.border = "1px solid red");

Would you like me to show examples of converting collections to arrays or best practices for manipulating DOM collections?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql