<h2>Adding an Event Listener to Multiple Elements Using a <code>forEach()</code> Loop</h2>
  <p>Open the console and click any of the buttons. The same event listener is added to each button using a <code>forEach()</code> loop.</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>

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;

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

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

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.