Nicc Nicc - 3 months ago 22
Javascript Question

Add eventListeners to each element from a NodeList

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

Answer

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)