I have following code
var el = document.querySelectorAll('.block');
console.log(el);
el.addEventListener('click', function () {
alert('hello');
}, false);
However, it returns an error Uncaught TypeError: Object #<NodeList> has no method 'addEventListener'
Why am I getting this error and how can I solve this issue?
I have following code
var el = document.querySelectorAll('.block');
console.log(el);
el.addEventListener('click', function () {
alert('hello');
}, false);
However, it returns an error Uncaught TypeError: Object #<NodeList> has no method 'addEventListener'
Why am I getting this error and how can I solve this issue?
Share Improve this question asked Feb 20, 2014 at 19:14 Om3gaOm3ga 32.9k45 gold badges149 silver badges230 bronze badges 1- querySelectorAll returns a Nodelist (an array like collection of dom nodes) and you can't attach an event listener to this. You will have to loop them and attach the event handler to the individual dom nodes – Mark Walters Commented Feb 20, 2014 at 19:17
2 Answers
Reset to default 8Because, exactly as the error message tells you NodeList
s 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);
}