Feb 252017
 
 February 25, 2017  Posted by at 6:10 am HTML & CSS, JS & TS  Add comments

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.

untitled-picture

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

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

What is 4 + 3 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)