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');
else
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) {...})
});