<main>
  <h2>Adding an Event Listener to Multiple Elements Using a <code>for...of</code> Loop + IIFE</h2>
  
  <p>Open the console and click any of the buttons. The same event listener is added to each button using a <code>for...of</code> loop along with an immediately invoked function that passes the current element of the loop back into the function.</p>

  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
  <button>Button 4</button>
  <button>Button 5</button>
  
  <p class="msg"></p>

</main>
body {
  font-family: Arial, sans-serif;
  font-size: 20px;
  padding: 0 20px;
}

main {
  text-align: center;
  margin: 0 auto;
  max-width: 800px;
}

p {
  text-align: left;
  padding: 0 20px;
}

code {
  color: firebrick;
}

.msg {
  text-align: center;
  color: red;
}

button {
  margin-bottom: 8px;
}
console.clear();

let btns = document.querySelectorAll('button');

for (i of btns) {
  (function(i) {
    i.addEventListener('click', function() {
      document.querySelector('.msg').innerHTML = i.innerHTML;
    });
  })(i);
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.