Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get all elements with onclick in them?

I am looking for a way to list all elements that have onclick event on a page.

like image 484
toli Avatar asked Jan 22 '23 01:01

toli


2 Answers

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.

like image 162
Josh the Goods Avatar answered Jan 24 '23 13:01

Josh the Goods


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);
        }
    }
}
like image 35
Matas Vaitkevicius Avatar answered Jan 24 '23 15:01

Matas Vaitkevicius