Skip to content

Home

Add event listener to all targets

Attaches an event listener to all the provided 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

More like this

Start typing a keyphrase to see matching snippets.