I'm trying to add an event listener to all elements with a class of section, however it only applies it to the last object in the node list.
var section = document.querySelectorAll('.section');
for(var i=0;i<section.length;i++){
var elem = section[i];
elem.addEventListener('click', function () {move (elem)}, false);
}
Is there a way I can add the event listener for each one?
In JavaScript, event listeners have to be attached to individual elements. You can't attach them to an array or node list of matching elements like you might in jQuery.
The addEventListener() methodYou can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.
appendChild(newListItem); // add created "li" element to "ul" newListItem. className = "item"; // add class to new "li" element newListItem. appendChild(x); // add a "span" to new "li" element var itemText = document. getElementById("newInput"); // read current input value itemText.
The issue is that there's no block scope in JavaScript. So elem
is overwritten each iteration, instead of being declared as a new variable each time. The only way to declare new variables in each iteration is through a function:
for(var i = 0; i < section.length; i++){
(function(elem) {
elem.addEventListener('click', function() { move(elem); }, false);
})(elem);
}
But addEventListener
sets this
to the element, so in your case you can neatly do:
for(var i = 0; i < section.length; i++){
elem.addEventListener('click', function () { move(this); }, false);
}
that's because you are referencing elem
and i
inside function. I can suggest trying
var section = document.querySelectorAll('.section');
for(var i=0;i<section.length;i++){
var handler = (function(ind){
return function () {
move (section[ind]);
}
})(i)
elem.addEventListener('click', handler, false);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With