DHTML Methods
DOM Level 1 Specification.
Replaces an existing child element with a new child element.
object.replaceChild ( oNewNode, oOldNode )
oNewNode |
Required. The new element to be inserted into the document. Elements can be created with the createElement method. |
oOldNode |
Required. The existing element to be replaced. |
Returns the node being replaced in the list.
This method replaces the child node oOldNode with oNewNode in the list of children, and returns the old node. If the new child is not specified, or null
, the old node is removed without a replacement.
The node to be replaced must be an immediate child of the parent object. The new node must be a node created with the createElement method.
This operation depends on the value of the nodeType property. If oNewNode is a DocumentFragment object, oOldNode is replaced by all of the DocumentFragment children, which are inserted in the same order. If the oNewNode is already in the tree, it is first removed.
This sample demonstrates replacing a bold element from a div with an italic element using the replaceChild method.
Click anywhere in this sentence to toggle this word between bold and italic.
<script language="JavaScript">
function replaceElement ( ) {
var oChild=Div1.children ( 0 );
var sInnerHTML = oChild.innerHTML;
if ( oChild.tagName=="B" ) {
oNewNode=document.createElement ( "I" );
Div1.replaceChild ( oNewNode, oChild );
oNewNode.innerHTML=sInnerHTML
}
else {
oNewNode=document.createElement ( "B" );
Div1.replaceChild ( oNewNode, oChild );
oNewNode.innerHTML=sInnerHTML
}
}
</script>
<div id=Div1 onclick="replaceElement ( )">
Click anywhere in this sentence to toggle this
<b>word</b> between bold and italic.</div>
appendChild, removeChild