Question

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.

Was it helpful?

Solution

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>

OTHER TIPS

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top