Iris Classon
Iris Classon - In Love with Code

Array not an array? Why forEach() can't be found

The other day I was scraping some information from the Dropbox site. The content was comments on my second draft on my book Loose Candy- which (at the time, this might have changed) were not downloadable. I had gotten feedback through various sources and I wanted to collect everything in one place.

The comment elements had a specific class, so I traversed the document and grabbed all the elements that had that particular class. Using the ‘.foreach()’ function in JavaScript I would iterate through the fetched collection of elements and append them to a string that I could later export. However, if you were to try to do that you would encounter the same error I came across.

One might think that the return value from ’ .getElementsByClassName()’ function (or other DOM interface functions) would be enumerable and behave like an array- but it’s not. It’s not an array, and it does not have a foreach() function. A -foreach call would yield:

Uncaught TypeError: result .foreach is not a function

The fix is easy. ECMAScript 6 has an Array.from() function that takes any array-like or iterable object and turns it into an array.

Instead of result.foreach()

You can could do:

Array.from(result).foreach()

 

For more on arrays, NodeList and HTMLCollection read this discussion on StackOverflow

Comments

Leave a comment below, or by email.


Last modified on 2017-02-25

comments powered by Disqus