DOM Clone Nodes

Duplicating nodes in XML documents

📋 What is Cloning Nodes?

Cloning creates exact copies of existing nodes in your XML document. This is useful when you need duplicate elements with the same structure, saving time instead of creating everything from scratch.


// Clone a node
var copy = originalNode.cloneNode(true);

// Add the clone to document
parentNode.appendChild(copy);
                                    

Clone Methods

The cloneNode() method is your main tool for duplicating nodes. It accepts a parameter that determines whether to copy child nodes or just the element itself.

📄

Shallow Clone

Copies only the node itself

node.cloneNode(false);
📚

Deep Clone

Copies node and all children

node.cloneNode(true);
🔗

Independent Copy

Clone is separate from original

// Changes don't affect original
âš¡

Fast Duplication

Faster than creating from scratch

// Efficient for templates

🔹 Shallow Clone (false)

A shallow clone copies only the element itself, without its children:

// Parse XML
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(
    "<book><title>Original</title><author>John</author></book>", 
    "text/xml"
);

// Get book element
var originalBook = xmlDoc.getElementsByTagName("book")[0];

// Shallow clone (no children copied)
var shallowCopy = originalBook.cloneNode(false);

console.log("Original:", originalBook.outerHTML);
console.log("Shallow:", shallowCopy.outerHTML);

Output:

Original: <book><title>Original</title><author>John</author></book>
Shallow: <book/>

🔹 Deep Clone (true)

A deep clone copies the element and all its children:

// Parse XML
var xmlDoc = parser.parseFromString(
    "<book id='1'><title>XML Guide</title><author>Jane</author></book>", 
    "text/xml"
);

// Get book element
var originalBook = xmlDoc.getElementsByTagName("book")[0];

// Deep clone (all children copied)
var deepCopy = originalBook.cloneNode(true);

console.log("Original:", originalBook.outerHTML);
console.log("Deep Copy:", deepCopy.outerHTML);

Output:

Original: <book id="1"><title>XML Guide</title><author>Jane</author></book>
Deep Copy: <book id="1"><title>XML Guide</title><author>Jane</author></book>

🔹 Modifying Cloned Nodes

Clones are independent - you can modify them without affecting the original:

// Parse XML
var xmlDoc = parser.parseFromString(
    "<library><book id='1'>Original Book</book></library>", 
    "text/xml"
);

// Clone the book
var original = xmlDoc.getElementsByTagName("book")[0];
var clone = original.cloneNode(true);

// Modify the clone
clone.setAttribute("id", "2");
clone.firstChild.nodeValue = "Cloned Book";

// Add clone to library
xmlDoc.documentElement.appendChild(clone);

console.log(xmlDoc.documentElement.outerHTML);

Output:

<library>
  <book id="1">Original Book</book>
  <book id="2">Cloned Book</book>
</library>

🔹 Cloning Multiple Times

Use cloning to create multiple copies efficiently:

// Parse XML with template
var xmlDoc = parser.parseFromString(
    "<library><book><title></title><author></author></book></library>", 
    "text/xml"
);

// Get template
var template = xmlDoc.getElementsByTagName("book")[0];

// Book data
var books = [
    {title: "Book 1", author: "Author A"},
    {title: "Book 2", author: "Author B"},
    {title: "Book 3", author: "Author C"}
];

// Clone and customize
books.forEach(function(data, index) {
    var clone = template.cloneNode(true);
    clone.getElementsByTagName("title")[0].textContent = data.title;
    clone.getElementsByTagName("author")[0].textContent = data.author;
    
    if (index > 0) { // Don't add first (it's the template)
        xmlDoc.documentElement.appendChild(clone);
    }
});

// Remove or update template
template.getElementsByTagName("title")[0].textContent = books[0].title;
template.getElementsByTagName("author")[0].textContent = books[0].author;

console.log(xmlDoc.documentElement.outerHTML);

Output:

<library>
  <book><title>Book 1</title><author>Author A</author></book>
  <book><title>Book 2</title><author>Author B</author></book>
  <book><title>Book 3</title><author>Author C</author></book>
</library>

🔹 Practical Use Case

Clone a complex structure and customize it:

// Parse XML with detailed book
var xmlDoc = parser.parseFromString(
    `<library>
        <book id="1">
            <title>JavaScript Basics</title>
            <author>John Doe</author>
            <price currency="USD">29.99</price>
            <stock>50</stock>
        </book>
    </library>`, 
    "text/xml"
);

// Clone the book structure
var original = xmlDoc.getElementsByTagName("book")[0];
var newBook = original.cloneNode(true);

// Customize the clone
newBook.setAttribute("id", "2");
newBook.getElementsByTagName("title")[0].textContent = "Advanced JavaScript";
newBook.getElementsByTagName("author")[0].textContent = "Jane Smith";
newBook.getElementsByTagName("price")[0].textContent = "39.99";
newBook.getElementsByTagName("stock")[0].textContent = "30";

// Add to library
xmlDoc.documentElement.appendChild(newBook);

console.log(xmlDoc.documentElement.outerHTML);

Output:

<library>
  <book id="1">
    <title>JavaScript Basics</title>
    <author>John Doe</author>
    <price currency="USD">29.99</price>
    <stock>50</stock>
  </book>
  <book id="2">
    <title>Advanced JavaScript</title>
    <author>Jane Smith</author>
    <price currency="USD">39.99</price>
    <stock>30</stock>
  </book>
</library>

🧠 Test Your Knowledge

What parameter creates a deep clone with all children?