XML DOM - Clone Node


In this chapter, we will discucss the Clone Node operation on XML DOM object. Clone node operation is used to create a duplicate copy of the specified node. cloneNode() is used for this operation.


This method returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes. The duplicate node has no parent ( parentNode is null) and no user data.


The cloneNode() method has the following syntax −

Node cloneNode(boolean deep)
  • deep − If true, recursively clones the subtree under the specified node; if false, clone only the node itself (and its attributes, if it is an Element).

  • This method returns the duplicate node.


The following example (clonenode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a deep copy of the first Employee element.

<!DOCTYPE html>
         function loadXMLDoc(filename) {
            if (window.XMLHttpRequest) {
               xhttp = new XMLHttpRequest();
            } else // code for IE5 and IE6 {
               xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            return xhttp.responseXML;
         xmlDoc = loadXMLDoc("/dom/node.xml");

         x = xmlDoc.getElementsByTagName('Employee')[0];
         clone_node = x.cloneNode(true);

         firstname = xmlDoc.getElementsByTagName("FirstName");
         lastname = xmlDoc.getElementsByTagName("LastName");
	 contact = xmlDoc.getElementsByTagName("ContactNo");
	 email = xmlDoc.getElementsByTagName("Email");
         for (i = 0;i < firstname.length;i++) {
               '+contact[i].childNodes[0].nodeValue+',  '+email[i].childNodes[0].nodeValue);

As you can see in the above example, we have set the cloneNode() param to true. Hence each of the child element under the Employee element is copied or cloned.


Save this file as clonenode_example.htm on the server path (this file and node.xml should be on the same path in your server). We will get the output as shown below −

Tanmay Patil, 1234567890, tanmaypatil@xyz.com
Taniya Mishra, 1234667898, taniyamishra@xyz.com
Tanisha Sharma, 1234562350, tanishasharma@xyz.com
Tanmay Patil, 1234567890, tanmaypatil@xyz.com

You will notice that the first Employee element is cloned completely.