+ 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

18th Apr 2021, 8:26 PM
salar vahidi
salar vahidi - avatar
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 } ) } ); } );
18th Apr 2021, 8:43 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar
+ 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...})...
18th Apr 2021, 8:37 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar
+ 2
thank you. I thought because NodeList object is not a real array it will not work with forEach, but it worked
18th Apr 2021, 9:12 PM
salar vahidi
salar vahidi - avatar
+ 1
salar vahidi it is not a real array .. it is an Array-Like ... Read about it in MDN
18th Apr 2021, 9:19 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar