Latest web development tutorials

XML DOM - clone node

Examples

Try - Example

The following example uses XML files the Books.xml .
Function loadXMLDoc () , in an external JavaScript is used to load the XML file.

Copy a node and append it to an existing node
This example uses cloneNode () to copy a node and append it to the root node of the XML document.


Copy nodes

cloneNode () method creates a copy of the specified node.

cloneNode () method has one parameter (true or false). This parameter indicates whether the cloned node includes all attributes and child nodes of the original node.

The following code fragment copies the first <book> node and appends it to the root node of the document:

Examples

xmlDoc=loadXMLDoc("books.xml");

oldNode=xmlDoc.getElementsByTagName('book')[0];
newNode=oldNode.cloneNode(true);
xmlDoc.documentElement.appendChild(newNode);

//Output all titles
y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
{
document.write(y[i].childNodes[0].nodeValue);
document.write("
");
}

Output:

Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML
Everyday Italian

try it"

Examples explain:

  1. Use loadXMLDoc () to " the Books.xml " into xmlDoc
  2. Get nodes to be copied
  3. Use cloneNode method to copy nodes to the "newNode" in
  4. Adding a new node to the root node of the XML document
  5. All output documents of title all book