I have following code
var el = document.querySelectorAll(\'.block\');
console.log(el);
el.addEventListener(\'click\', function () {
alert(\'hello\');
},
Because, exactly as the error message tells you NodeLists don't have an addEventListener method. You should iterate over the nodelist, and addEventListener
to each element within – assuming that you want to add N listeners.
Alternately, select only a single element, and the remainder of your code will work as written.
The method querySelectorAll() returns a NodeList which is a collection of nodes.
Hence you need to iterate it to attach event listeners
var el = document.querySelectorAll('.block');
for(var i=0; i < el.length; i++){
el[i].addEventListener('click', function () {
alert('hello');
}, false);
}