How to change href of <a> tag on button click through javascript

Chauhan picture Chauhan · Dec 6, 2010 · Viewed 470.7k times · Source

How to change the href attribute value of an <a/> tag through Javascript on button click ?

<script type="text/javascript">
  function f1()
  {
    document.getElementById("abc").href="xyz.php"; 
  }
</script>

<a href="" id="abc">jhg</a>
<a href="" id="" onclick="f1()">jhhghj</a>

Answer

Nick Craver picture Nick Craver · Dec 6, 2010

Without having a href, the click will reload the current page, so you need something like this:

<a href="#" onclick="f1()">jhhghj</a>

Or prevent the scroll like this:

<a href="#" onclick="f1(); return false;">jhhghj</a>

Or return false in your f1 function and:

<a href="#" onclick="return f1();">jhhghj</a>

....or, the unobtrusive way:

<a href="#" id="abc">jhg</a>
<a href="#" id="myLink">jhhghj</a>

<script type="text/javascript">
  document.getElementById("myLink").onclick = function() {
    document.getElementById("abc").href="xyz.php"; 
    return false;
  };
</script>