How can I add "href" attribute to a link dynamically using JavaScript?

Pavel picture Pavel · Jan 14, 2011 · Viewed 348.6k times · Source

How can I add the href attribute to a link dynamically using JavaScript?

I basically want to add a href attribute to <a></a> dynamically (i.e. when the user clicks on specific image in the website).

So from:

<a>Link</a>

I need to go to:

<a href="somelink url">Link</a>

Answer

stecb picture stecb · Jan 14, 2011
var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"