XML DOM replaceChild() method

Makala ya Mfano ya Node

Definition and usage

The replaceChild() method can replace one child node with another.

If the replacement is successful, this method can return the replaced node, if the replacement fails, it returns NULL.

Syntax:

nodeObject.replaceChild(new_node,old_node)
Parameter Description
new_node Required. Specify the new node.
old_node Required. Specify the node to be replaced.

Tips and notes

Note:Internet Explorer will ignore the generated blank text nodes between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the following example, we will use a function to check the node type of the first child node.

The node type of an element node is 1, so if the first child node is not an element node, it will move to the next node and continue to check if this node is an element node. The entire process will continue until the first element child node is found. Through this method, we can get the correct method in Internet Explorer and Mozilla.

Tip:For more information on the differences between XML DOM in IE and Mozilla browsers, please visit our DOM Browser Chapter.

Instance

In all examples, we will use the XML file books.xml, and JavaScript function loadXMLDoc()

The following code snippet can replace the <title> element of the first <book> element:

//check if first child node is an element node
function get_firstchild(n)
{
var x=n.firstChild;
while (x.nodeType!=1)
  {
  x=x.nextSibling;
  }
return x;
}
xmlDoc=loadXMLDoc("books.xml");
//create a title element and a text node
var newNode=xmlDoc.createElement("title");
var newText=xmlDoc.createTextNode("Giada's Family Dinners");
//Kuondoa ujumbe wa mwingine kwa mwingine wa jina
newNode.appendChild(newText);
//Kuwaambia mwingine wa mwingine wa mwanafunzi kwa mwingine mpya
var x=xmlDoc.getElementsByTagName("book")[0];
x.replaceChild(newNode,get_firstchild(x));
//Muhtasari yote ya jina
var y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
  {
  document.write(y[i].childNodes[0].nodeValue);
  document.write("<br />");
  }

Muhtasari:

Vifungo vya Giada's Family
Harry Potter
XQuery Kick Start
Mafunzo ya XML

Makala ya Mfano ya Node