Published:

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());
});

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some Vanilla JS Help?

Search fiverr to find help quickly from experienced Vanilla JS developers.



Supported by