0

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/";
4
  • document.getElementById('whatever').href="some text" or setAttribute if you want to change the DOM and not just the element property Commented Mar 22, 2016 at 4:53
  • You should also be able to use Jquery, $("#href").attr("href","Hello World"); Commented Mar 22, 2016 at 4:56
  • Why is the solution in the question? Commented Mar 22, 2016 at 4:58
  • Only the Universe truly knows. Commented Mar 22, 2016 at 4:59

1 Answer 1

1

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/");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.