简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM