Home javascript Why is there an error like.addEventListener is not a function?

Why is there an error like.addEventListener is not a function?




There is a code like this and it works:

function openLikeBlock () {
 var like = document.getElementById ("like");
 like.addEventListener ('click', function (e) {
  e.preventDefault ();
  if (! this.classList.contains ('open'))
   this.classList.add ('open');
   this.classList.remove ('open');

But if you add ClassName then there will be an error:

var like = document.getElementsByClassName ("like");

Uncaught TypeError: like.addEventListener is not a function

I need exactly the class, since there are several such blocks on the page (that’s why I use this )

Question: how do I get an element by class, not ID?

Answer 1, authority 100%

Because getElementsByClassName returns a collection of elements and the collection does not have a method addEventListener

for a solution, you can simply go through the returned collection. like this:

[]. forEach.call (like, function (el) {
  el.addEventListener ('click', function (e) {...})

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions