Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Event Listener of an Element

Is there any way to get the list of all event listeners of an element on the HTML page using JavaScript on that page.

Note: I know we can see them with Chrome dev tools event listeners but I want to log/access see list using the JavaScript of the page.

Also, I know we can get them through jQuery but for that, we also have to apply the events using jQuery, but I want something that would be generic so I could also access the event listeners applied to other elements such as web components or react components.

like image 593
Yasir 768 Avatar asked Oct 19 '25 22:10

Yasir 768


1 Answers

If you really had to, a general way to do this would be to patch EventTarget.prototype.addEventListener:

const listeners = [];
const orig = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(...args) {
  if (this instanceof HTMLElement) {
    listeners.push({
      type: args[0],
      fn: args[1],
      target: this,
    });
  }
  return orig.apply(this, args);
};

document.body.addEventListener('click', () => console.log('body clicked'));
console.log(listeners[0].fn);
click this body

To find listeners attached to an element, iterate through the listeners array and look for targets which match the element you're looking for.

To be complete, also patch removeEventListener so that items can be removed from the array when removed.

If you need to watch for listeners attached via on, then you'll have to do something similar to the above to patch the HTMLElement.prototype.onclick getter/setter, and for each listener you want to be able to detect.

That said, although you said you want a generic solution, rather than patching built-in prototypes, it'd be better to add the listeners through jQuery or through your own function.

like image 102
CertainPerformance Avatar answered Oct 21 '25 13:10

CertainPerformance