<main>
<h2>Adding an Event Listener to Multiple Elements Using a <code>for...of</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>for...of</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>
</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) {
i.addEventListener('click', function() {
document.querySelector('.msg').innerHTML = this.innerHTML;
});
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.