Search code examples
javascripthtmleventsnodelisthtmlcollection

How do I add an event listener to each element in an html collection?


function eventAdded(i) {
  console.log(inputs[i]);
}
var inputs = document.querySelectorAll('.js-capture__input input');
for (i = 0; i <= inputs.length; i++) {
  console.log(inputs[i]);
  inputs[i].addEventListener('change', eventAdded);
}

I am managing to log each inputs[i] to the console. inputs[i] exists. But I am getting Uncaught TypeError: Cannot read property 'addEventListener' of undefined

How is this not defined if I can log each one to the console? Can someone please explain like I'm 5?


Solution

  • Like @CertainPerformance said, your error is having i <= inputs.length instead of i < inputs.length.

    The difference is that in the first case, you are going outside the boundaries of the array.

    For example, if you have an array of 5 elements (remember arrays are 0-based):

    0
    1
    2
    3
    4
    

    When you check using i <= inputs.length, this is what's happening:

    0 <= 5: true
    1 <= 5: true
    2 <= 5: true
    3 <= 5: true
    4 <= 5: true
    5 <= 5: true
    6 <= 5: false
    

    So instead of iterating 5 times, you are iterating 6 times. The last one (i=5), is not within the array boundaries (its upper bound is 4).

    function eventAdded(i) {
      console.log(inputs[i]);
    }
    var inputs = document.querySelectorAll('.js-capture__input input');
    for (var i = 0; i < inputs.length; i++) {
      console.log(inputs[i]);
      inputs[i].addEventListener('change', eventAdded);
    }