Iterating over result of getElementsByClassName using Array.forEach
Leverage Array.from() to transform the HTMLCollection into an iterable array. This allows you to use the forEach for direct element iteration because elements are shy and won't iterate themselves π.
Step-by-step guide to using Array.forEach with getElementsByClassName
Solution 1: Directly applying Array.prototype.forEach.call
As a JavaScript ninja, use Array.prototype.forEach.call()
to apply forEach
directly on the HTMLCollection.
Solution 2: Using spread syntax for ES6 fancy pants
In the land of ES6, you can use the spread syntax to convert your chained container HTMLCollection
into a butterfly array and it will happily obey forEach
.
Solution 3: Stumbling over older browser's stone path
For those brave souls who still venture in the realms of Internet Explorer and older browsers, beware! Gatekeepers called ES6 features might block your path. Fear not, the Babel
tool will transform them into harmless ES5, so your journey can continue.
Solution 4: Unleash the power of querySelectorAll
Switch getElementsByClassName
with querySelectorAll
if you want your code to not only work but also have a model-like performance.
Digging deeper : Exploring alternative ways and gotchas
Avoiding the tricks of sneaky not-so HTMLElements
Applying functions on DOM elements is fun, but watch out! Some elements might be impostor aliens, they're not HTMLElements. Use instanceof
to detect and avoid them.
For the traditionalists: Using for...of loop
If you stick to old school ways, the for...of
loop will hold your hand. It'll faithfully traipse through each HTMLCollection
, no sweat.
What's the deal with NodeList and HTMLCollection
NodeLists and HTMLCollections are not just species from the DOM Zoo, they have different wand capabilities. NodeList from querySelectorAll
has its own built-in forEach
magic spell:
Was this article helpful?