Advertisement
Advertisement



Question

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>
2015/09/10
1
93
9/10/2015 8:56:23 PM

Accepted Answer

var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"
2013/08/02
161
8/2/2013 5:00:23 PM

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

To add any attribute, just use the setAttribute method on the DOM object:

a = document.getElementById(...);
a.setAttribute("href", "somelink url");
2011/01/14

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

Then, add something like this in the javascript function that you're calling:

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

This way the link will look like this:

<a href="somelink">Link</a>
2016/12/28

document.getElementById('link-id').href = "new-href";

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

2016/12/27

Source: https://stackoverflow.com/questions/4689344
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]