XML DOM Clone Nodes

To create a copy of a specified node, we use the cloneNode() method. The parameter of the cloneNode() method can either be true or false, thus indicating if all the attributes and child nodes of the original node should be included in the cloned node or not.


<?xml version="1.0" encoding="UTF-8"?>
  <book category="Child">
    <title lang="en">ABC</title>
    <author>Author Name</author>
  <book category="Internet">
    <title lang="en">Basics</title>
    <author>Author 1</author>
    <author>Author 2</author>


<!DOCTYPE html>
<p id="hello"></p>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
xhttp.open("GET", "books.xml", true);
function myFunction(xml) {
    var x, y, cloneNode, i, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('book')[1];
    cloneNode = x.cloneNode(true);
    // Output all titles
    y = xmlDoc.getElementsByTagName("title");
    for (i = 0; i < y.length; i++) { 
        txt += y[i].childNodes[0].nodeValue + "<br>";
    document.getElementById("hello").innerHTML = txt; 


In the above example, we are loading the “books.xml” in the xmlDoc to get the old node copied. It means that we will clone the second <book> node into “newNode”, to append the new node to the root node of the XML document.

Please Share