Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

.forEach not a For loop

Does any one know why I can't use a forEach loop. console say Uncaught TypeError: myList.forEach is not a function

const myList = document.getElementsByTagName('li');

/* doesn't work */

myList.forEach( li => { li.style.color = 'purple';
});

/* works*/

for(let i=0; i<myList.length; i++){ myList[i].style.color = 'purple'; }

1 Answer

Hi Daniele,

As far as I know, when you use getElementsByTagName it returns a special data type known as an HTMLCollection. This isn't an Array, but does have some array-like behaviours. When you iterate over it, you need to reference the indexes of the values, so a for loop is necessary. If it was a true Array or an Object, you could use forEach().

In ES2015 I think you can create an array from an HTMLCollection using Array.from(myHTMLCollection).

I'm sure someone else will be able to explain it better! But I hope this helps a bit!

Thanks David. It works now.

const newList = Array.from(myList);