Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1747 How can I change the HREF attribute of a link when a form button is clicked?

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>

©2018 Martin Webb