How to Add an Event Listener to Multiple Elements in JavaScript

If you want to add an event listener to multiple elements in JavaScript, there are a couple of approaches you can take. In this article, we will explore two methods: using a loop and leveraging event bubbling. Method 1: Using a Loop The first method involves using a loop to iterate over the elements and attach the event listener individually. Here’s an example: document.querySelectorAll('.some-class').forEach(item => { item.addEventListener('click', event => { // handle click }); }); In the above code, querySelectorAll() is used to select all elements with a specific class....