You are here: irt.org | FAQ | JavaScript | Link | Q1747 [ previous next ]
The following works in Internet Explorer 4+ and Netscape Navigator 6+ using the id attribute to identify the required link. In other browsers you need to supply the original href attribute value of the link for the code to trawl through all the links in the document looking for the appropriate link:
<html> <head> <script language="JavaScript"><!-- function findLinkByHref(href) { for (var i=0; i<document.links.length; i++) { if (document.links[i].href == href) return i; } return -1; } function changeLinkHref(id,newHref,oldHref) { if (document.links.length > 0) { if (document.getElementById) { document.getElementById(id).href = newHref; } else if (document.all) { document.all[id].href = newHref; } else { var index = findLinkByHref(oldHref); if (index > -1) document.links[index].href = newHref; } } } //--></script> </head> <body> <a id="myLink" href="http://www.mozilla.org">somewhere</a> <form> <input type="button" value="Change href" onClick="changeLinkHref('myLink','http://www.irt.org','http://www.mozilla.org')"> </form> </body> </html>