Search code examples
javascriptaddeventlistenerevent-delegation

addEventListener to multiple elements, using Event Delegation (JavaScript)


I'm trying to add an event to multiple elements. For now, I have this code and it works. But, I want to use Event Delegation and move the listener to the parent element (deck). I've tried so many solutions found here on Stack, but none of them it's working.
Question, which will be the best way to delegate the event?

HTML

<section class="deck">
    <div class="card">
        <div class="front"></div>
        <div class="back">
            <img src="#" alt="">
        </div>
    </div>
    <div class="card">
        <div class="front"></div>
        <div class="back">
            <img src="#" alt="">
        </div>
    </div>
    ...

JavaScript

var card = document.querySelectorAll(".card");
var len = card.length;

for (let i = 0; i <= len; i++) {
    card[i].onclick = function () {
        this.classList.add("foo");
    }
}

Solution

  • Simple event delegation could look like this in your case:

    var deck = document.querySelector(".deck");
    
    deck.addEventListener('click', function (e) {
      var target = e.target
    
      if (target.classList.contains('card')) {
        target.classList.add('foo') 
      }
    })
    

    Note, this check target.classList.contains('card') is necessary so that you add class foo only to elements with class .card.