Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I’m getting an ".addEventListener is not a function" error. I am stuck on this:

var comment = document.getElementsByClassName("button"); function showComment() {   var place = document.getElementById('textfield');   var commentBox = document.createElement('textarea');   place.appendChild(commentBox); } comment.addEventListener('click', showComment, false); 
<input type="button" class="button" value="1"> <input type="button" class="button" value="2"> <div id="textfield"> </div> 
like image 623
leecarter Avatar asked Aug 15 '15 18:08

leecarter


People also ask

How do you fix addEventListener is not a function?

To solve the "addEventListener is not a function" error, make sure to call the addEventListener() method on a valid DOM element, or the document or window objects, and place the JS script tag at the bottom of the body tag in your HTML.

What is the use of event listener in Javascript?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.


1 Answers

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 ) ;  } 
like image 98
Nikhil Aggarwal Avatar answered Oct 21 '22 04:10

Nikhil Aggarwal