0

I want to add eventListener Click to each element of a NodeList. I've tried the following

var test = document.getElementsByClassName('productLnk')

function theTest (element,index,array){
 element.addEventListener('click',function(){
   console.log('hello')
 })
}

test.forEach(theTest)

It returns test.forEach is not a function

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Nicc
  • 777
  • 3
  • 8
  • 19

1 Answers1

3

You need to convert NodeList to Array for iterating using Array#forEach method. In ES6 use Array.from method

Array.from(test).forEach(theTest)

or in older browser use Array#slice with Function#apply or Function#call.

[].slice.call(test).forEach(theTest)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 1
    But more importantly, don't do it! Attach 1 event listener to the root of the list and distinguish between the sources from there. – ZenMaster Sep 01 '16 at 16:10
  • 1
    @ZenMaster It depends on the usage. Sometimes your approach is not as optimal as adding independent listeners to each item. – Derek 朕會功夫 Sep 01 '16 at 16:12
  • @Derek朕會功夫 Do tell. – ZenMaster Sep 01 '16 at 16:13
  • 1
    @ZenMaster : who knows all the elements are in the same roots... that's just an assumption... – Pranav C Balan Sep 01 '16 at 16:17
  • @PranavCBalan While theoretically you might be right (and even then - finding that root shouldn't be that complex), the example is `document.getElementsByClassName('productLnk')` ... So it is safe to assume that there is a list of products involved. There _is_ a common root. – ZenMaster Sep 01 '16 at 23:08
  • @ZenMaster : if they are in multiple root elements.... why should want to make it that much complex ???? – Pranav C Balan Sep 02 '16 at 05:04
  • @PranavCBalan Because attaching multiple event handlers has an impact on performance? – ZenMaster Sep 03 '16 at 01:13
  • @ZenMaster : yes I know .. but we can't attach to the parent on all scenario ... in this particular case even we don't know the DOM structure – Pranav C Balan Sep 03 '16 at 05:31