Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

javascript - get all elements with onclick in them?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...