AddEventListener On NodeList


Answer :

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!


There actually is a way to do this without a loop:

[].forEach.call(nodeList,function(e){e.addEventListener('click',callback,false)}) 

And this way is used in one of my one-liner helper libraries - nanoQuery.


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android SDK Location Should Not Contain Whitespace, As This Cause Problems With NDK Tools