0

I want to access all the buttons i created, but i can only access the last one. The first console.log() (nr1), gives me the textContent of all the buttons that i press. But the last console.log() only "works" (or gives me) with the last button/textContent (the last object in the array).

            opt.onclick = function(){

                for(item of arr){

                    let btn = document.createElement('button')
                    let btnText = document.createTextNode(item.name)
                    btn.appendChild(btnText)
                    forum.appendChild(btn)

                    btn.onclick = function(){
                        console.log(btn.textContent) //Nr.1
                        if(btn.textContent === item.name){
                            console.log(item.name) //Nr.2
                        }
                    }



                }

            }
Mr.Ulis
  • 157
  • 6
  • 1
    The `item` variable is global. After the loop has completed, it contains the last value, so it's always going to be the one printed out. Just add a `let` before it to make it local to each iteration `for (let item of arr)` – blex Feb 14 '20 at 21:44
  • https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Teemu Feb 14 '20 at 21:44
  • @blex thank you. I didnt know that it made a difference (let) – Mr.Ulis Feb 14 '20 at 21:46

0 Answers0