Published: January 06 2023

JavaScript - Add Event Listener to Multiple Elements in Vanilla JS

This is a super quick post to show how to add an event listener to multiple HTML elements in pure JavaScript.

I had to do this recently to handle click events on one or more modal popup elements in a single page.

JavaScript event bubbling

Events in javascript are propagated (or bubbled) up the DOM tree from the target element through its parents all the way to the root (html) element, document and window objects.

So to listen for events on multiple elements you can add a single event listener to the document object and check the target element.

The below snippet effectively adds a 'click' event listener to all elements with the CSS class 'jw-modal' to close modal popups on background click. For a demo of the code see Vanilla JS + CSS - Modal Popup (Dialog) Tutorial with Example.

// close modals on background click
document.addEventListener('click', event => {
    if (event.target.classList.contains('jw-modal')) {
        closeModal();
    }
});


Looping over elements with forEach

Alternatively you can add multiple event listeners by looping over multiple elements with the javascript forEach method.

The below snippet gets the same result as the one above by looping over the targeted elements. It uses querySelectorAll() to get all elements with the CSS class ('jw-modal') and adds a click event listener to each.

The only drawback of this approach is it won't cover dynamic elements that are added later, whereas the event bubbling example will include dynamic elements because it's listening on the root document object.

document.querySelectorAll('.jw-modal').forEach(el => {
    el.addEventListener('click', event => closeModal());
});

 


Need Some Vanilla JS Help?

Search fiverr for freelance Vanilla JS developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by