I am looking for a way to list all elements that have onclick
event on a page.
Edited to answer further questions...
I'm not sure exactly what you're asking, but I suspect you're looking for a way to see if there has been code attached to an element's onclick event? If so, try this:
var allElements = document.getElementsByTagName('*');
for ( var i = 0; i<allElements.length; i++ ) {
if ( allElements[i].className !== 'theClassNameYoureLookingFor' ) {
continue;
}
if ( typeof allElements[i].onclick === 'function' ) {
// do something with the element here
console.log( allElements[i] );
}
}
If you'd like some information about the actual function attached to the onclick event, you'll need to make use of Firebug or something similar to output the function and examine it as it will have been possibly generated at runtime (ie the function declaration might not just be sitting on the page where it could theoretically be accessed easily). Try using the code provided above, but instead of
console.log( allElements[i] );
do
console.log( allElements[i].onclick );
Now, in firebug, you can mouse over the functions it prints and see their code.
Answer from @Josh the Goods didn't work for me, I had to slightly modify it.
var allElements = document.getElementsByTagName('*');
for (var i = 0; i < allElements.length; i++) {
if ($._data(allElements[i])['events'] != undefined
&& $._data(allElements[i])['events']['click'] != undefined) {
console.log(allElements[i]);
for (var ii = 0; ii < $._data(allElements[i])['events']['click'].length; ii++) {
console.log($._data(allElements[i])['events']['click'][ii].handler);
}
}
}
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