There is such a code 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'); else this.classList.remove('open'); }); } 

But if you add a 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 (therefore I use this )

Question: how to do, so that I could receive an element by class, and not ID?

1 answer 1

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

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

 [].forEach.call(like,function(el){ el.addEventListener('click', function (e) {...}) }); 
  • one
    I will add to the answer that it is more convenient to use the method (s) of querySelector / querySelectorAll and even better browser support. - Deonis
  • Thanks, always help out) - Nikita Shchypylov
  • @Deonis, querySelector is not a collection :) - user207618
  • @Other, you forgot to add: " Your KO ": D - Deonis
  • @Deonis, Minute pedantry :) - user207618