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

How to add href attribute to link dynamically using JavaScript?

Basically, I want to add the href attribute to <a></a> dynamically (that is, when a user clicks on a specific image on a website).

So from:

 <a>Link</a> 

I need to go to:

 <a href="somelink url">Link</a> 
+43
javascript html
Jan 14 2018-11-11T00:
source share
5 answers
 var a = document.getElementById('yourlinkId'); //or grab it by tagname etc a.href = "somelink url" 
+88
Jan 14 '11 at 8:50
source share

I assume that you know how to get the DOM object for the <a> element (use document.getElementById or some other method).

To add any attribute, simply use the setAttribute method of the DOM object:

 a = document.getElementById(...); a.setAttribute("href", "somelink url"); 
+13
Jan 14 '11 at 8:52
source share

I know that this has already been answered, but since this post helped me solve my decision, I would like to publish it.

I originally tried

 <a href='somelink' class='button-css'>Click Me</a> 

and it almost worked. The text was a little off center and just not entirely clear. Then I tried:

 "<a href='SomeLink'><input type='button' class='button-css' value='Button Text' /></a>" 

My button looks great and the link works.

0
Dec 11 '12 at 6:10
source share
 document.getElementById('link-id').href = "new-href"; 



I know this is an old post, but here is a one-liner that might be more suitable for some people.

0
Dec 27 '16 at 18:52
source share

First try changing <a>Link</a> to <span id=test><a>Link</a></span> .

Then add something like this to the javascript function that you are calling:

 var abc = 'somelink'; document.getElementById('test').innerHTML = '<a href="' + abc + '">Link</a>'; 

Thus, the link will look like this:

 <a href="somelink">Link</a> 
0
Dec 28 '16 at 7:42 on
source share



All Articles