Skip to content

XML DOM: Clone Nodes

How to use the cloneNode() method in JavaScript to create deep or shallow copies of XML elements while preserving attributes and child nodes.

Let's see how to clone an element node with cloneNode().

Clone a Node with cloneNode() Method

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

The cloneNode() method has a parameter (true or false). This parameter indicates if the cloned node should include all attributes and child nodes of the original node.

Example: clone the first <book> node and appends it to the root node of the document:

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