JavaScript: replacing links in HTML

Got a strange one here. I have a requirement to replace text dynamically on a flat HTML page. I scouted around and found a simple substitution script on teh intarweb which I adapted to test:


<span id="b1">Answer</span> | <span id="b2">Question</span>

<p id="t">Change this</p>

<script type="text/javascript">
var text1 = "<a href='test'>asdf</a>";
function f1() {document.getElementById("t").firstChild.nodeValue="You've changed";}
function f2() {document.getElementById("t").firstChild.nodeValue=text1;}

//define the links to change
document.getElementById("b1").onclick = f1;
document.getElementById("b2").onclick = f2;
</script>

It works fine - click on “Answer” and “Change this” changes to “You’ve changed”; click on “Question” though, and the variable text1 that I set renders the link exactly as “<a href=‘test’>asdf</a>”. Not as “asdf”.

Can I do anything to parse the string so that it renders as HTML rather than plain text? Or should I be using a different method?

Thanks!

You can use the somewhat kludgy innerHTML to do this:



function f2() {
     document.getElementById("t").innerHTML=text1;
}


The DOM method is a little more work, clear the element, add the link/text:



function f2() {
     an_obj = document.getElementById("t");
     while(an_obj.firstChild){
            an_obj.removeChild(an_obj.firstChild);
     }
     an_anchor = document.createElement("a");
     an_anchor.setAttribute("href","http://gosomewhere");
     an_anchor.appendChild(document.createTextNode("hello"));
     an_obj.appendChild(an_anchor);
}


I didn’t test any of this…

Thanks, larsenmtl. Both do exactly what I want.

The only problem is, after I click either of your functions, neither link works. I tried adding a “return false” to them but no dice, they’re still disabled. Any ideas?

Also, I don’t think any method at all will get me the W3C double-A accessibility standard that the client wanted…

I believe that your f1 no longer works after clicking my f2. You could do two things–>

Use innerHTML on F1



function f1() {
    document.getElementById("t").innerHTML="You've changed";
}


Clear “t” and recreate



function f1() {
     an_obj = document.getElementById("t");
     while(an_obj.firstChild){
            an_obj.removeChild(an_obj.firstChild);
     }
     an_obj.appendChild(document.createTextNode("You've Changed"));
}


BTW, I believe the DOM method (version 2 in each code example) is considered the correct way to do this. The innerHTML method is considered poor form. I still use it all the time though, :cool:

Aha, of course. Working fine now.

That DOM thing looks really complicated. I need to build a large list with 17 elements inside <LI> tags, so I might have to go for the innerHTML option despite everything.

Thanks so much for your help!