0

Why this piece of code does not run outside of a handler function?

[...document.querySelectorAll('.movement__row')].forEach((row, i) => {
  console.log(i);
  if (i % 2 === 0) row.style.backgroundColor = 'orangered';
});
TunA
  • 21
  • 3
  • 4
    Which handler function? Use the [browser console (dev tools)](//webmasters.stackexchange.com/q/8525) (hit `F12`) and read any errors. How does it fail? [Edit] your post and include a [mre]. What is `document.querySelectorAll('.movement__row').length` “outside of a handler function”? Is it `0`? By “handler” function, do you mean a `DOMContentLoaded` event listener? Is your ` – Sebastian Simon Sep 14 '21 at 05:55
  • 1
    A wild guess - are you running this code *before* the elements are on the page? – VLAZ Sep 14 '21 at 05:57
  • 1
    Why aren't you styling using CSS? `.movement__row:nth-child(even)` – Rickard Elimää Sep 14 '21 at 06:00
  • Thanks @SebastianSimon I will learn how to ask question probably before posting next time. By the way, this code is from a tutorial I am following. In the video the author wrote this and it didn't work, he then said it need to be inside an event handler function but didn't explain much. He created a random click event and it really works. I try to explain it myself since there is no error notifications but I cannot find an answer. I try to log 'i' to the console, it do not work but when I try to do otherthing like after this piece of code it works normally . – TunA Sep 15 '21 at 16:25
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 20 '21 at 09:30

0 Answers0