XML DOM cloneNode() Method

Node Object Reference Manual

Definition and Usage

The cloneNode() method can create an exact copy of the specified node.

This method can return the copied node.

Syntax:

nodeObject.cloneNode(include_all)
Parameter Description
include_all Required. If the logical parameter is set to true, the cloned node will clone all child nodes of the original node.

Return value

Copy of the current node.

Description

This method will copy and return a copy of the node it calls. If a parameter of true is passed to it, it will also recursively copy all descendants of the current node. Otherwise, it will only copy the current node.

The returned node does not belong to the document tree, and its parentNode property is null.

When copying an Element node, all its attributes will be copied. However, it should be noted that the event listener functions registered on the current node will not be copied.

Example

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

The following code snippet can clone the first <book> node and then add it to the end of the node list:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book')[0];
var cloneNode=x.cloneNode(true);
xmlDoc.documentElement.appendChild(cloneNode);
//Output all titles
var y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
  {
  document.write(y[i].childNodes[0].nodeValue);
  document.write("<br />");
  }

Output:

Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML
Everyday Italian

Try It Yourself (TIY)

cloneNode() - Clone Node

Node Object Reference Manual