Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

javascript - dom method for replacing nodes

In addition to removing nodes, the DOM offers a way to replace one node with another. The replaceChild method accomplishes this. As with removeChild above, replaceChild needs to be called from the element that contains the node you wish to replace.

replaceChild takes two arguments: a reference to the new node, and another to the node being replaced. The following example creates a new SPAN element containing a text node, and uses it to replace an existing SPAN.

<script type="text/javascript">
function replaceSpan(){

    var newSpan = document.createElement("span");
    var newText  
	document.createTextNode("on top of the astounded zebra");
    newSpan.appendChild(newText);

    var para = document.getElementById("example3");
    var spanElm = document.getElementById("ex3Span");
    var replaced = para.replaceChild(newSpan,spanElm);
}
</script>


<p id="example3">The quick brown fox jumps <span id="ex3Span">over the lazy dog</span>.</p>


<button onclick="replaceSpan();">Call replaceSpan()</button>
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS