0

So whenever I run my code this

const sections = document.getElementsByTagName("section");
let colors = ["#ffc933", "#09ff00", "#00ccff", "#2b72ff", "#5436ff", "#dd54ff", "#5a0070", "05c9ff", "ff5405", "fa2d2d"];
for(ele in sections)
{
    console.log("Yes");
    ele.style.backgroundColor = colors[Math.floor(Math.random() * 10)];
}

it always returns an error saying that the property style of ele can't be assigned to since it is undefined. This doesn't make any sense to me since it says for the elements in sections so all the ones that are there should be iterated through so nothing should be undefined.

  • 1
    You should use `for..of..` instead of `for..in..`, see [this answer](https://stackoverflow.com/a/22754453/16688813) for more details. – Tom Jan 20 '22 at 15:32
  • You can use `document.querySelectorAll('section').forEach(ele => { ... })` instead. –  Jan 20 '22 at 15:38

0 Answers0