Search code examples
javascriptaddeventlistenernodelist

addEventListener on NodeList


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

Solution

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