For loop for HTMLCollection elements
Iterate an HTMLCollection with a for loop or convert it with Array.from() and apply forEach:
For loop:
Array.from() + forEach:
Essential facts
Working with HTMLCollections to manipulate the DOM is a common scenario. Here are some reliable methods to iterate over these objects.
Cruising with a for...of loop
The for...of
loop is widely supported in modern browsers and provides an efficient option to iterate over HTMLCollections:
Array conversion for expanded functionality
Sometimes you need more power. Converting an HTMLCollection
to an Array
enables the use of array-specific methods:
Rolling by with Array.prototype.forEach
Before Array.from()
hit the stage, Array.prototype.forEach
was borrowed often to iterate HTMLCollections:
Albeit old, this approach remains crucial for legacy browsers missing support for iterable HTMLCollections.
Exercise caution with for...in
The for...in
loop is designed for object properties, not numerical indexes:
Using this loop with HTMLCollections may lead to unexpected results. Beware!
Decoding Symbol.iterator
The Symbol.iterator
property lets us use for...of
on NodeLists. Notably, modern browsers have added this property to HTMLCollection
:
Be aware! Overriding native prototypes can affect globally, so consider potential side effects.
Going beyond the basics
Array conversion using the spread operator
Less common but equally useful, the spread operator copies the collection into an array:
QuerySelectorAll() and the iterable NodeList
NodeLists are similar to HTMLCollections but behave better with forEach
, thanks to the querySelectorAll
method:
Ensuring maximum compatibility
Browser support is essential when writing cross-platform code. For wide compatibility with older browsers, the traditional for loop still shines:
Hints of functional programming
Embrace functional programming with methods like map
and reduce
by converting HTMLCollections:
Striking a balance
When choosing an iteration method, consider the balance between performance, readability, and functionality. Also, consider how well it aligns with your coding style and project architecture.
Was this article helpful?