replaceChild
Summary
Replaces an existing child node with a new child node.
Syntax
var replacedNode = node.replaceChild(/* see parameter list */);
Parameters
newChild
- Data-type
- DOM Node
The new node to be inserted into the document.
oldChild
- Data-type
- DOM Node
The existing node to be replaced.
Return Value
Returns an object of type DOM NodeDOM Node
IHTMLDOMNode
Returns a reference to the object that is replaced.
Examples
This example uses the replaceChild method to replace a bold element from a div with an italic element.
<!doctype html>
<head>
<script>
function replaceElement()
{
var Div1 = document.getElementById("Div1");
//The first child of the div is the bold element.
var oChild=Div1.children(0);
var sInnerHTML = oChild.innerHTML;
if (oChild.tagName=="B")
{
oNewChild=document.createElement("I");
Div1.replaceChild(oNewChild, oChild);
oNewChild.innerHTML=sInnerHTML
}
else
{
oNewChild=document.createElement("B");
Div1.replaceChild(oNewChild, oChild);
oNewChild.innerHTML=sInnerHTML
}
}
</script>
</head>
<body>
<div id="Div1" onclick="replaceElement()">
Click anywhere in this sentence to toggle this <strong>word</strong>
between bold and italic.</div>
</body>
Notes
The node to be replaced must be an immediate child of the parent object. The new node must be created using the createElement method. This property is accessible at run time. If elements are removed at run time, before the closing tag is parsed, areas of the document might not render.
Related specifications
- DOM Level 3 Core
- Recommendation
Attributions
Mozilla Developer Network : [Node.replaceChild Article]
Microsoft Developer Network: [replaceChild Method Article]