javascript - Event listener giving error -
i have code example:
<html> <input class="basketquantity" type=number>basket item 1</input> <input class="basketquantity" type=number>basket item 2</input> </html> <script> quantityinputs = document.queryselectorall(".basketquantity"); for(var in quantityinputs){ quantityinputs[i].addeventlistener('change', function(){ console.log(quantityinputs[i]); }); } </script>
when run error message:
typeerror: quantityinputs[i].addeventlistener not function
could tell me why happening?
quantityinputs = document.queryselectorall(".basketquantity");
first of quantityinputs
nodelist
object. so
for(var in quantityinputs){ console.log(i); }
will return enumerable properties - quantityinputs
object , prototype chain, not own (just quantityinputs
enumerable properties). for .. in
return length
field , item
enumerable properties prototype chain , properties not dom nodes , don't have addeventlistener
method.
you must use object.keys
:
var nodearray = [].slice.call(document.queryselectorall(".basketquantity")); object.keys(nodearray).foreach(function (node) { // node.addeventlistener });
or
or for .. in
hasownproperty
check:
quantityinputs = document.queryselectorall(".basketquantity"); for(var in quantityinputs){ if (quantityinputs.hasownproperty(i)) { // quantityinputs[i].addeventlistener } }
or
in future (es6) can use in case for .. of
loop:
var quantityinputs = document.queryselectorall("basketquantity"); (var node of quantityinputs) { console.log(node.addeventlistener); }
note(thanks @teemu):
also have error in handler i
:
quantityinputs[i].addeventlistener('change', function(){ console.log(quantityinputs[i]);// return value of quantityinputs last });
so better use this
addeventlistener
target:
quantityinputs[i].addeventlistener('change', function(){ console.log(this); });