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 One Solution

My for...in loop isn't working.

const cards = document.getElementsByClassName('card');
for (const card in cards) {
 card.style.backgroundColor = 'skyblue'; 
}

I'm trying to do a for...in loop to iterate through each h2 element, but's not working. I get a TypeError: Cannot set property 'backgroundColor' of undefined.

What did I do wrong??

Thanks!!

Reggie Williams
Reggie Williams
Treehouse Teacher

Hey JASON PETERSEN have you tried checking the value of cards with a console.log statement?

Reggie, good idea. When I do that it shows an HTMLCollection. Also when I do a different type of for loop it works correctly. So I did something wrong in my for loop.

2 Answers

Instead of for (const card in cards) {, try for (const card of cards) {. Your current code loops over the properties of cards rather than the iterable objects of cards.

That did it! Thanks!!

I don't know that I understand the difference tho. What's the difference between 'enumerable properties' and 'iterable objects'?

The collection has default properties such as length, and default methods. backgroundColor and other things you set with CSS are also properties. Objects include things like the elements in your collection, or elements of an array.

You could use your for ... in loop to see what it gives you.

for (const p in cards) {
  console.log(p + ": " + cards[p]);
}

Try removing the 'const' in the loop.

Tried that, no dice.