I'm trying to iterate over a NodeList to assign each node a color from an array that was declared named 'colors', iterating through the array.
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; //PLEASE DON'T CHANGE THIS LINE!
//YOU CODE GOES HERE:
const allSpans = document.querySelectorAll('span')
for(let span of allSpans){
span.style.color = colors[span]
}
Expected: each span to have been set from a color in the colors array. (The first span now red, Second orange, etc.)
I ended up doing this to get the objective completed:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; //PLEASE DON'T CHANGE THIS LINE!
//YOU CODE GOES HERE:
const allSpans = document.querySelectorAll('span')
let element = 0
for(let span of allSpans){
span.style.color = colors[element]
element
}
but I feel like it is sloppy and that there should be a way to do it much like the way that I mentioned in the first block of code. If anyone could help me that would be great so that I can better my understanding of NodeLists
CodePudding user response:
Use a different loop, examples:
for...in
:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const allSpans = document.querySelectorAll('span')
for(const key in allSpans){
allSpans[key].style.color = colors[key]
}
for
:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const allSpans = document.querySelectorAll('span')
for (let i = 0; i < allSpans.length; i = 1) {
allSpans[i].style.color = colors[i]
}
forEach
:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const allSpans = document.querySelectorAll('span')
allSpans.forEach((span, index) => {
span.style.color = colors[index]
})
CodePudding user response:
you need to use a counter variable to keep track of the current index in the colors array as you iterate through the allSpans NodeList.
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const allSpans = document.querySelectorAll('span');
let colorIndex = 0;
for (let span of allSpans) {
span.style.color = colors[colorIndex];
colorIndex = (colorIndex 1) % colors.length;
}
CodePudding user response:
You can use the Array forEach
method which also provides an index value for each iteration.
const allSpans = document.querySelectorAll('span');
Array.from(allSpans).forEach((el,i) => {
el.style.color = colors[i];
});
CodePudding user response:
You could convert the nodelist to an array like so
Array.from(allSpans)
Then iterate over that using map or forEach
const updatedSpans = Array.from(allSpans).map((span, idx) => {
span.style.color = colors[idx]
return span
}
I would say your solution is fine though!