最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS error object has no method addEventListener - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 8

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);
}
发布评论

评论列表(0)

  1. 暂无评论