I'm having a problem with adding onClick events to <a> tags. The attribute is never added at all, but no errors are shown in the JavaScript console. I'm using Firefox 3.0.10.

Here's my code:

<script type="text/javascript">
function setAJAXAttributes() {
	var domain = new RegExp("(" + window.location.host + ")|(^\\/.*)|(^[\\w\\d]*\\.[\\w\\d]{2,})", "i");
	var links = document.getElementsByTagName("a");

	for (var i=0; i<links.length; i++) {
		if (domain.test(links[i].href)) {
			links[i].onClick = "getPage('" + links[i].href + "');";
			alert("Added onClick: " + links[i].href);
			links[i].target = "_blank";

<a href="http://www.daniweb.com">DaniWeb</a><br/>
<a href="http://www.example.com/ajax/test.html">Testing absolute path</a><br/>
<a href="/ajax/test.html">Testing page relative parent path</a><br/>
<a href="test.html">Testing name path</a><br/>

<script type="text/javascript">setAJAXAttributes();</script>

I made sure that the conditional statement was working correctly by adding an alert to the onClick portion, and the alerts worked fine. However, the onClick event is never added, not on Firefox or IE7.

It also works fine if I change each <a> tag's href to javascript: getPage(); , but I don't want to change what shows in the status bar.

7 Years
Discussion Span
Last Post by essential
Featured Replies

Hi there,

the onClick event, must be all in lowercase onclick :

links[i].[b]onclick[/b] = "getPage('" + links[i].href + "');";

Thanks! That worked perfectly. Tried that method earlier, but not in combination with all lowercase onclick .

Here is the line that is fixed:

links[i].onclick = function() { getPage(this.href); return false; };

+rep :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.