“.addEventListener is not a function” why does this error occur?

The problem with your code is that the your script is executed prior to the html element being available. Because of the that var comment is an empty array.

So you should move your script after the html element is available.

Also, getElementsByClassName returns html collection, so if you need to add event Listener to an element, you will need to do something like following

comment[0].addEventListener('click' , showComment , false ) ; 

If you want to add event listener to all the elements, then you will need to loop through them

for (var i = 0 ; i < comment.length; i++) {
   comment[i].addEventListener('click' , showComment , false ) ; 
}

Leave a Comment