Martin Erlic
Martin Erlic

Reputation: 5665

Inject string into a href with javascript?

In the same way that I can inject some text into a div with javascript, how can I inject a string into the href portion of an html anchor?

var div = document.getElementById('hrefId');
div.innerHTML = "Some dandy text!";

Something like this?

var hrefVar = document.getElementById('hrefId');
hrefVar.innerHTML = "Some dandy text!";

The problem is that it populates the space between <a></a>, as opposed to filling up the href with text, which is what I need to get the link to work.

<a href="" id="href"></a>

Solution:

var hrefVar = document.getElementById('hrefId');
hrefVar.href = "http://www.microsoft.com/";

Upvotes: 0

Views: 713

Answers (1)

James111
James111

Reputation: 15903

Since this was never officially answered I'll post it here.

Todo this with pure javascript:

var hrefVar = document.getElementById('hrefId');
hrefVar.href = "http://www.microsoft.com/";

Or could do it in one line

var hrefVar = document.getElementById('hrefId').href="http://www.microsoft.com/";

jQuery:

$("#hrefId").attr("href","http://www.microsoft.com/");

Upvotes: 1

Related Questions