-1

I've struggled with this for a while and have been following the documentaitons to a 'T' as decribed here: https://www.w3schools.com/js/js_htmldom_eventlistener.asp But I'm still getting errors. My code:

let card = document.getElementsByClassName('card');
card.addEventListener('click', cardClicked);

function cardClicked(){

    console.log('clicked');
}

I get the following error:

card.addEventListener is not a function

There must be some basic programming concept I'm completely missing. Can someone help?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ab3d_work
  • 185
  • 3
  • 16
  • 1
    getElementsByClassName returns a collection of objects and you need to choose one of them to apply the event listener to. Right now you are trying to add a click listener to a collection. – takendarkk Aug 05 '18 at 21:09
  • Interesting. I just used querySelector vs etElementsByClassName and it worked. Thank you! – ab3d_work Aug 05 '18 at 21:15
  • However, I just realized it only clicks once..... do you know what I would use to make something be clicked multiple times? – ab3d_work Aug 05 '18 at 21:20

1 Answers1

0

The right way would be to subscribe to click event like this:

document.addEventListener("click", function cardClicked(){
    console.log('clicked');
});

No need to use any query selectors here.

UPDATED: If you want to subscribe only specific class elements to event, you may try to do it this way:

let cards = document.getElementsByClassName('card');

 Array.from(cards).forEach(function (element) {
     element.addEventListener('click', function cardClicked() {
        console.log('clicked');
     });
 });
Pavel Vasiluk
  • 317
  • 2
  • 12