2

i'm trying to loop an HTMLCollection and i want to add a onclick event inside each element.

for(var page of pages){
   page.onclick = () => {
       console.log(count)
   }
   count += 1
}

Well, the problem is actually that when i click the button, it shows up only the last counted number (5), but not actually the counted element. How to fix it? Thanks.

Diaskyyy
  • 29
  • 6
  • 2
    move `count += 1` inside the onclick handler – Trash Can Mar 15 '22 at 16:39
  • i can't because i want to increment other stuffs on in the onclick function – Diaskyyy Mar 15 '22 at 16:45
  • For the question to be complete, it should have desired/expected output in addition to actual output. What is `count` supposed to represent? The index of `page` in `pages`? – outis Mar 15 '22 at 16:47
  • Avoid the `onclick` property. For this specific use case, `((count) => page.addEventListener("click", () => console.log(count))(count);` can be used instead of `page.onclick = () => { console.log(count) }`. But what do you need `count` for? There’s very likely a much better solution. – Sebastian Simon Mar 15 '22 at 16:47

2 Answers2

1
for(var page of pages){
   page.onclick = () => {
       console.log(count++)
   }
}

I guess this is what you want ? increment after a click ? and not in the for loop

Thibaud
  • 1,059
  • 4
  • 14
  • 27
  • Ok, and how could i access to the page element? – Diaskyyy Mar 15 '22 at 16:41
  • in the page element – Diaskyyy Mar 15 '22 at 16:41
  • @Diaskyyy you can add an argument event inside the function like this ``` page.onclick = (event) => { console.log(count++, event) }``` event will have a lot of data that you may want about the event (click) but also on the element clicked – Thibaud Mar 15 '22 at 16:45
1

One way would be to use a for Loop.

for (let count = 0; count < pages.length; count++) {
   pages[count].onclick = () => {
       console.log(count)
   }  
}
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79