Add event listener to all targets

JavaScript, Browser, Event · Apr 22, 2021

Attaches an event listener to all the provided targets.

  • Use Array.prototype.forEach() and EventTarget.addEventListener() to attach the provided listener for the given event type to all targets.
const addEventListenerAll = (targets, type, listener, options, useCapture) => {
  targets.forEach(target =>
    target.addEventListener(type, listener, options, useCapture)
addEventListenerAll(document.querySelectorAll('a'), 'click', () =>
  console.log('Clicked a link')
// Logs 'Clicked a link' whenever any anchor element is clicked

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • JavaScript Event Handling

    Event handling needs to be done right in JavaScript. Pick up some tips and tricks to create a better user experience.

    Collection · 15 snippets

  • Remove event listeners from target

    Detaches an event listener from all the provided targets.

    JavaScript, Browser · Apr 22, 2021

  • Add event listener to element

    Adds an event listener to an element with the ability to use event delegation.

    JavaScript, Browser · Oct 21, 2020

  • Add multiple listeners

    Adds multiple event listeners with the same handler to an element.

    JavaScript, Browser · Oct 22, 2020