0

I am attempting to add an eventListener to each html element from a nodelist, and pass that same html element as an argument to the callback function. My code looks like so.

let programs = document.getElementsByClassName('program-name')
for (i = 0; i < programs.length; i++){
    programs[i].addEventListener("click", () => testFunc(programs[i]))
}
function testFunc(program) {
    console.log(program)
}

The problem is that I am expecting console.log(program) to log an html element to the console, however all the log is undefined

  • your html please? – Manish Jan 16 '17 at 18:44
  • 1
    `programs[i]` is undefined because `i` is out-of-bounds. The reason is that you are using a global variable for `i` that will, by the time `testFunc` is called for the first time, already equal `programs.length` (after the loop) which is out of bounds. Check out the suggested duplicate – nem035 Jan 16 '17 at 18:45
  • 2 possible solutions. 1 ) use `for (let i = 0; i < programs.length;i ++)` it will keep a local copy of `i` in each round of the loop. 2) use the event object, and grab the event.s currentTarget `programs[i].addEventListenr("click", (event) => testFunc(event.currentTarget)` – Patrick Denny Jan 16 '17 at 18:51

1 Answers1

1

Instead of using closure (as suggested in the comments), you can make use of event object passed to the handler as such:

programs[i].addEventListener("click", (evt) => testFunc(evt.currentTarget))

Then, the HTML element that was clicked will be passed to the callback.

Adam Wolski
  • 5,448
  • 2
  • 27
  • 46