".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>

Solution 1:

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 ) ; 
}

Solution 2:

document.getElementsByClassName returns an array of elements. so may be you want to target a specific index of them: var comment = document.getElementsByClassName('button')[0]; should get you what you want.

Update #1:

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment() {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}

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

Update #2: (with removeEventListener incorporated as well)

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment(e) {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
  for (var i = 0; i < numComments; i++) {
    comments[i].removeEventListener('click', showComment, false);
  }
}

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

Solution 3:

var comment = document.getElementsByClassName("button");

function showComment() {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}

for (var i in comment) {
  comment[i].onclick = function() {
    showComment();
  };
}
<input type="button" class="button" value="1">
<input type="button" class="button" value="2">
<div id="textfield"></div>