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>
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.
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.
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 ) ; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With