0

The problem asks to change the 7 spans through selecting all the spans and then changing the color of each of them. Im seeing that this solution works. And also there was another way I found. However, is there any way I can make this solution without a nested for loop? I feel like I'm missing something about using arrays or something. Thanks.

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; //PLEASE DON'T CHANGE THIS LINE!

`enter code here`//YOU CODE GOES HERE:
const spanners = document.querySelectorAll('span');
for( i = 0 ; i < colors.length ; i++){
    for(let span of spanners){
        span.style.color = colors[i]
        i++;
    }
}
Garthy
  • 1
  • 1
  • You're doing `i++` for every colour, _times_ every span. It's inside both loops – Jeremy Thille Jan 26 '21 at 15:58
  • `.querySelectorAll()` returns a `NodeList`, which has a `.forEach()` method, that passes the current element and index to the callback. Check the examples on [here](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) and [here](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach) – Andreas Jan 26 '21 at 16:06

1 Answers1

0

If there are 7 colours and 7 spans, you can just do :

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

const spanners = document.querySelectorAll('span');

for( let i in colors){
    spanners[i].style.color = colors[i];
}
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • `for...in...` is for objects and not arrays – Andreas Jan 26 '21 at 16:03
  • Try `for( let i in ['red', 'orange', 'yellow']) console.log(i)` in your console. Day not wasted, you learned something :) – Jeremy Thille Jan 26 '21 at 16:05
  • `for...in...` will return index of i and `for...of...` will return element – Hyetigran Jan 26 '21 at 16:07
  • I know it works. But this doesn't change the original purpose of [`for...in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) which is to iterate over the properties (including those from the prototype chain) of an object – Andreas Jan 26 '21 at 16:08
  • [Why is using “for…in” for array iteration a bad idea?](https://stackoverflow.com/questions/500504/why-is-using-for-in-for-array-iteration-a-bad-idea) – Andreas Jan 26 '21 at 16:08
  • Meh, so long as it works. Day not wasted, I learned something. Thanks – Jeremy Thille Jan 26 '21 at 16:11