views:

320

answers:

3

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.

+2  A: 

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

karim79
It will not append, but rather replace the text.
Artem Barger
Thanks @Artem, added '+'
karim79
innerText is not supported by all browsers.
Ionuț G. Stan
@Ionus G. Stan - you're right, amended the answer
karim79
+3  A: 
var anchor = document.getElementById('anchorID');
anchor.innerHTML = anchor.innerHTML + " I just did something.";

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

AutomatedTester
Did I misunderstand something? It does not work: http://pastebin.com/m7f634ebe
Masi
The example you posted has two elements with he same id. id is meant to be unique in a page, try using a different id for your a element.
tschaible
+1  A: 

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"&gt;
<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="&gt;Click here</a>
  </div>
</body>
</html>
tschaible
really cool, but it appends "Dsi7x-A89Mw" to the end of "Click here", and not "http://www.youtube.com/watch?v=".
Masi
In that case you want to use anchor.href ... i've amended my answer.
tschaible
Great! Big thanks :) Solved.
Masi