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 trialJASON PETERSEN
14,266 PointsMy 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!!
JASON PETERSEN
14,266 PointsReggie, 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
jb30
44,807 PointsInstead 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
.
JASON PETERSEN
14,266 PointsThat did it! Thanks!!
I don't know that I understand the difference tho. What's the difference between 'enumerable properties' and 'iterable objects'?
jb30
44,807 PointsThe 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]);
}
Scott Brantley
6,084 PointsTry removing the 'const' in the loop.
JASON PETERSEN
14,266 PointsTried that, no dice.
Reggie Williams
Treehouse TeacherReggie Williams
Treehouse TeacherHey JASON PETERSEN have you tried checking the value of
cards
with a console.log statement?