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?
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
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With