0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
nasi
  • 1
  • 4
  • Please add at the bottom of the page, after **ALL** js finished to run `alert(document.body.innerHTML)` I might miss the exact JS but you get my meaning, I hope. – Itay Moav -Malimovka May 12 '11 at 00:14
  • I added it after my onclick code, at the end of function that contains onclick, and at the end of my JS file, but nothing changed – nasi May 12 '11 at 00:39
  • ahhh, that is for debug purposes, what is the output, to the screen, of that. – Itay Moav -Malimovka May 12 '11 at 00:45
  • I have a text box that when I double click on a word in it, JS runs. when I added alert(document.body.innerHTML) it shows the content of that text box in an alert box. – nasi May 12 '11 at 00:56

1 Answers1

1

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • The
    cannot hold, it is too late - http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
    – tobyodavies May 12 '11 at 01:09
  • thanks. just one more question. I want to add onclick to some of the links in the page not all of them and as I said links don't have any id. I was wondering if I still can use document.links? more over if parsing HTML is the reason why it works properly when I use onClick="alert("hello");return false; – nasi May 12 '11 at 02:00