Easy Tutorial
❮ Prop Document Lastchild Met Element Comparedocumentposition ❯

XML DOM Clone Node


Try It Yourself - Example

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

Copy a node and append it to an existing node


Copy Node

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

The 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 snippet copies the first <book> node and appends it to the document's root node:

Example

xmlDoc = loadXMLDoc("books.xml");
x = xmlDoc.getElementsByTagName('book')[0];
cloneNode = x.cloneNode(true);
xmlDoc.documentElement.appendChild(cloneNode);

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

Output:

Example Explanation:

❮ Prop Document Lastchild Met Element Comparedocumentposition ❯