marcobiedermann
marcobiedermann

Reputation: 4915

JavaScript: Get all elements which have an event bind to them

Is there a way in JavaScript to get all elements on the page which have an event bind to them. I know you can get all events an a particular event, but is there a way the all elements?

Upvotes: 3

Views: 2370

Answers (2)

marcobiedermann
marcobiedermann

Reputation: 4915

Thank you all for your help. I found this great snippet which loops over all elements on page and adds each elements which has an event bind to it to an array.

var items = Array.prototype.slice.call(
  document.querySelectorAll('*')
).map(function(element) {
  var listeners = getEventListeners(element);
  return {
    element: element,
    listeners: Object.keys(listeners).map(function(k) {
      return { event: k, listeners: listeners[k] };
    })
  };
}).filter(function(item) {
  return item.listeners.length;
});

Full credit to Dan: https://gist.github.com/danburzo/9254630

Upvotes: 2

Tiago Engel
Tiago Engel

Reputation: 3663

As suggested in the comments, you can use getEventListeners(document) on chrome dev tools, but if you want to use this inside your code, a possible solution is using a custon function to register the events and mantaining a list of elements that have events atached.

Code not ready to use, just an example

let elements = [];
function addEventListener(elem, event, cb) {
   elem.addEventListener(event, cb);
   elements.push(elem);
}

You will of course need to remove the element when the event is removed.

If you don't have control over all code that register events (which is quite common) you can monkey path the Node.prototype.addEventListener function. Which is not recomended (you can read more here). But it is a possibility...

Upvotes: 1

Related Questions