Skip to content Skip to sidebar Skip to footer

How To Use Javascript To Find All Elements Which Have Event Listeners?

A custom button
Another custom button

Solution 1:

There is no native javascript api that allows you to find event listeners that were added using eventTarget.addEventListener.

You can still get events added using the onclick attribute whether the attribute was set using javascript or inline through html - in this case u are not getting the event listener, but you are getting the value of the onclickattribute which are two different things.

Javascript offers no api for doing so, because dom elements can be removed while event listeners still referencing them.

If you want to keep track of event listeners attached to dom elements you have to do that yourself.

Apart from that chrome has getEventListeners command line api which works with dom elements, however it is a developer tools command line api and so it only works when called from developer tools.

Solution 2:

There is no way, to do so directly with JavaScript.

However, you can use this approach and add an attribute while binding events to the elements.

document.getElementById('test2').addEventListener('keypress', function() { 
    this.setAttribute("event", "yes");
    console.log("foo");
  }
)
document.querySelectorAll('test3').forEach(item => {
    item.addEventListener('click', event => {
      this.setAttribute("event", "yes");
      console.log("bar");
    })
  })

document.getElementById('test4').onclick = function(event) {
  let target = event.target;
  this.setAttribute("event", "yes");

  if (target.tagName != 'li') {
     event.target.addClass('highlight');
  }
};

And this is how you can find the elements having events bind to them :

var eventElements = document.querySelectorAll("[event='yes']");
var countEventElements = eventElements.length;

Post a Comment for "How To Use Javascript To Find All Elements Which Have Event Listeners?"