Appending text in <a>-tags with Javascript

I now that I can insert text to <div> tag by :

<script type="text/javascript">
  function doSomething(){
    var lbl = document.getElementById('messageLabel');
    lbl.innerHTML = "I just did something.";    
  }  
</script>

</head>
<body>
  <div>
  <div id="messageLabel"></div>
  <input type="button" value="Click Me!" onclick="doSomething();" />

  </div>

My question: how can I append text to to a link?

Examples not working 1 and 2.

Upvotes: 1

Views: 14592

Answers (3)

tschaible
tschaible

Reputation: 7695

From the example you posted above, try using the code below instead. I changed the id of the div tag to be different from the link you're trying to change and changed the code to modify the href of anchor.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Javascript Debugging with Firebug</title>
<script type="text/javascript">
  function addLink(){
    var anchor = document.getElementById('link');
    anchor.href += "Dsi7x-A89Mw";
  }  
</script>

</head>
<body>
  <div>
  <div id="linkdiv"></div>
  <input type="button" value="Click Me!" onclick="addLink();" />

  <a id="link" href="http://www.youtube.com/watch?v=">Click here</a>
  </div>
</body>
</html>

Upvotes: 3

karim79
karim79

Reputation: 342635

innerText or textContent can be used to access the text of a tag:

var anchor = document.getElementById('something');
anchor.innerText += "some text";    

var anchor = document.getElementById('something');
anchor.textContent += "some text";

However, those are not cross-browser, so you would probably be better off using innerHTML:

var anchor = document.getElementById('something');
anchor.innerHTML += "some text";  

See this:

http://www.quirksmode.org/dom/w3c_html.html

Upvotes: 2

AutomatedTester
AutomatedTester

Reputation: 22418

var anchor = document.getElementById('anchorID');
anchor.innerHTML = anchor.innerHTML + " I just did something.";  

Should add "I just did something." to your current anchor text

Upvotes: 3

Related Questions