nasi
nasi

Reputation: 1

onclick generates a fault

I have a web page with some links (there is no id assigned to these links). I want to add onclick feature to these links. by looking at the source code of that web page I realized that I can add onclick to the links using the following code:

doc = doc.replace(/&sa=N\"/g, "&sa=N\" onClick=\"alertsomething();return false;\"");

function alertsomething(){
alert('hello');
}

but when the web page is loaded and I click on these links the alertsomething function doesn't work. it generates the following page:

Object not found!

The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

If you think this is a server error, please contact the webmaster.

Error 404 localhost 12/05/2011 10:00:29 AM Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1

I checked the following code and it works properly

doc = doc.replace(/&sa=N\"/g, "&sa=N\" onClick=\"alert("hello");return false;\"");

I am using IE7.

Upvotes: 0

Views: 809

Answers (1)

RobG
RobG

Reputation: 147413

Do not mess with the body.innerHTML unless you know exactly what you are doing. It will delete listeners that are added as DOM properties, also parsing HTML with a regular expression will certainly fail in any non-trivial page.

There is a document.links collection that is every link in the page, iterate over that and add your listener to each link. Or add a single click listener to the body and wait for clicks - if they come from a link, do your stuff.

Upvotes: 1

Related Questions