+ 1
why doesn't this loop work?
when I want to iterate through an array consisting of color values to style elements inside "bttn" node-list, it doesn't work(in the form of C[i]). but when I write the index number within the brackets like this: C[0], it works what's the problem and how should I fix it? https://code.sololearn.com/Wa54a61a6A11
4 odpowiedzi
+ 4
// a safe code for you
window.addEventListener(
'DOMContentLoaded', // when dom ready
function() {
var bttn = document.querySelectorAll('.btn'); // elements
var C = [
'red', 'green', 'purple'
]; // colors
bttn.forEach( // for all elements
function (el, i) {
el.addEventListener( // el onclick
'click',
function (e) {
e.target.style.color = C[i]; // the index of the .btn element will be kept here
}
)
}
);
}
);
+ 3
So many issues OK first do all of them inside of onload event listener or do it in a script tag in body tag,please don't do functions in a loop scope use :
document.querySelectorAll object has a bttn.forEach method use it..
use it as bttn.forEach((ele, i) => {ele.add...})...
+ 2
thank you. I thought because NodeList object is not a real array it will not work with forEach, but it worked
+ 1
salar vahidi it is not a real array .. it is an Array-Like ... Read about it in MDN