XML DOM replaceChild() method

Manual de referencia del objeto 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 will return 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 blank text nodes generated between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the following examples, 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 whether this node is an element node. This 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 functions 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("Cenas familiares de Giada");
//agregar el nodo de texto al nodo de título,
newNode.appendChild(newText);
//reemplazar el primer nodo hijo con el nodo nuevo
var x=xmlDoc.getElementsByTagName("book")[0];
x.replaceChild(newNode,get_firstchild(x));
//salida de todos los títulos
var y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
  {
  document.write(y[i].childNodes[0].nodeValue);
  document.write("<br />");
  }

Salida:

Cenas familiares de Giada
Harry Potter
XQuery Kick Start
Aprender XML

Manual de referencia del objeto Node