btn.eventListener is not a function!

1

When I want to add an event listener to an html object, the eventlistener is not a function error appears in the browser console, the code is as follows. This script is executed in a simple html file.

var btn = document.getElementsByClassName('btn');

btn.addEventListener('click', adding, false);

function adding(e){
  e.preventDefault();
  console.log(e);
}
    
asked by SERGIO 28.04.2018 в 23:30
source

1 answer

4

Because getElementsByClassName() returns in a array the number of found elements, therefore the variable btn is a array and then when trying to make addEventListener() it tells you that it is not a function.
Conclusion, what you should do is either go through all the elements of the array and add the events or tell them that only the first one creates the event (that if only if you know that it is only one).

In your case

Simply adding the index of the first array:

var btn = document.getElementsByClassName('btn');

btn[0].addEventListener('click', adding, false);

function adding(e){
  e.preventDefault();
  console.log(e);
}

Making a for

The best way for these cases is to create a for for all the elements found:

var btn = document.getElementsByClassName('btn');

for (var i = 0; i < btn.length; i++) {
  btn[i].addEventListener('click', adding, false);
}

function adding(e){
  e.preventDefault();
  console.log(e);
}
    
answered by 28.04.2018 / 23:47
source