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);
}