Skip to main content Accessibility Feedback

Attaching multiple elements to a single event listener in vanilla JS

Let’s say you have an accordion widget on your page, and you want to show or hide the corresponding content whenever one of five different links on a page is clicked.

In jQuery, these clicks are really easy to listen for:

$('.accordion-link').on('click', function () {
    // Do something...
});

The vanilla JS equivalent of .on(), addEventListener(), can only be attached to a single element, not a set of them like in jQuery. How would you handle this?

You could add a separate event listener for every single accordion link on the page, but that would be madness.

There’s an easier way: Event Bubbling. #

An alternate approach is to listen for all clicks on the page by attaching your event listener to the document element. You can then check if the clicked element has the selector you care about.

document.addEventListener('click', function (event) {
    if ( event.target.classList.contains( 'accordion-link' ) ) {
        // Do something...
    }
}, false);

This is known as event bubbling.

As a side benefit of this approach, you can dynamically add elements to the DOM without having to add additional event listeners. Everything just bubbles up and gets checked against our selector in real time.

Next, learn how to run the same code on multiple events with vanilla JavaScript. Bubbling not working for you? It may be related to the use capture argument.


🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips