addEventListener on NodeList

前端 未结 8 2249
轮回少年
轮回少年 2020-11-30 07:12

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 be

8条回答
  •  死守一世寂寞
    2020-11-30 07:52

    in es6, you can do a array from nodelist, using Array.from, e.g.

    ar_coins = document.getElementsByClassName('coins');
    Array
     .from(ar_coins)
     .forEach(addEvent)
    
    function addEvent(element) {
      element.addEventListener('click', callback)
    }
    

    or just use arrow functions

    Array
      .from(ar_coins)
      .forEach(element => element.addEventListener('click', callback))
    

提交回复
热议问题