Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Do href in JavaScript?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).


var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"

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");

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.


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>

More actual solution:

<a id="someId">Link</a>

const a = document.querySelector('#someId');
a.href = 'url';