Does NodeList support addEventListener. If not what is the best way to add EventListener to all the nodes of the NodeList. Currently I am using the code snippet as show below, is there a better way to do this.
var ar_coins = document.getElementsByClassName('coins'); for(var xx=0;xx < ar_coins.length;xx++) { ar_coins.item(xx).addEventListener('dragstart',handleDragStart,false); }
The querySelectorAll method returns a NodeList , so we are able to use the NodeList. forEach method to iterate over the result. We used the addEventListener to add a click event listener to every element in the collection. If you need a list of all of the available event types, check out this MDN events list.
forEach() The forEach() method of the NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order.
A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes). HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number. An HTMLCollection is always a live collection.
Using the once optionWe can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.
There is no way to do it without looping through every element. You could, of course, write a function to do it for you.
function addEventListenerList(list, event, fn) { for (var i = 0, len = list.length; i < len; i++) { list[i].addEventListener(event, fn, false); } } var ar_coins = document.getElementsByClassName('coins'); addEventListenerList(ar_coins, 'dragstart', handleDragStart);
or a more specialized version:
function addEventListenerByClass(className, event, fn) { var list = document.getElementsByClassName(className); for (var i = 0, len = list.length; i < len; i++) { list[i].addEventListener(event, fn, false); } } addEventListenerByClass('coins', 'dragstart', handleDragStart);
And, though you didn't ask about jQuery, this is the kind of stuff that jQuery is particularly good at:
$('.coins').on('dragstart', handleDragStart);
The best I could come up with was this:
const $coins = document.querySelectorAll('.coins') $coins.forEach($coin => $coin.addEventListener('dragstart', handleDragStart));
Note that this uses ES6 features, so please make sure to transpile it first!
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