TExcelTAD
Home › XML › DOM Clone Nodes

XML DOM Clone Nodes

Cloning makes a copy of a node. Because inserting an existing node moves it, cloning is how you duplicate content — copying a template record, repeating a block, or keeping a backup before you change something.

cloneNode(deep)

Call Copies
node.cloneNode(false) The node and its attributes only — no children (shallow)
node.cloneNode(true) The node, its attributes and all descendants (deep)
html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = new DOMParser().parseFromString(
      '<library><book id="b1" genre="fantasy"><title>The Hobbit</title><year>1937</year></book></library>', 'application/xml');
    const book = xmlDoc.querySelector('book');
    const s = new XMLSerializer();

    console.log('shallow:', s.serializeToString(book.cloneNode(false)));
    console.log('deep   :', s.serializeToString(book.cloneNode(true)));
  </script>
</body>
</html>

Note: Always pass the argument explicitly. Its default is false, so cloneNode() gives you an empty shell — a frequent source of "where did my children go?" bugs.

Copies are independent

A clone is detached (not in the tree) and completely separate from the original. Changing one doesn't affect the other:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = new DOMParser().parseFromString(
      '<library><book id="b1"><title>The Hobbit</title><price>8.99</price></book></library>', 'application/xml');
    const original = xmlDoc.querySelector('book');

    const copy = original.cloneNode(true);
    copy.setAttribute('id', 'b1-hardback');
    copy.querySelector('price').textContent = '24.00';
    xmlDoc.documentElement.appendChild(copy);

    for (const b of xmlDoc.querySelectorAll('book')) {
      console.log(b.getAttribute('id'), b.querySelector('title').textContent, b.querySelector('price').textContent);
    }
  </script>
</body>
</html>

Remember to change values that must stay unique, such as id attributes — the clone copies them exactly.

Templates: clone, fill, insert

A clean way to produce many similar elements is to keep one template element and clone it for each record:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = new DOMParser().parseFromString(`<report>
  <template>
    <row status="pending"><name/><score/></row>
  </template>
  <rows/>
</report>`, 'application/xml');

    const tpl = xmlDoc.querySelector('template > row');
    const rows = xmlDoc.querySelector('rows');
    const results = [['Aiko', 91], ['Bram', 67], ['Chidi', 78]];

    for (const [name, score] of results) {
      const row = tpl.cloneNode(true);
      row.querySelector('name').textContent = name;
      row.querySelector('score').textContent = score;
      row.setAttribute('status', score >= 70 ? 'pass' : 'retake');
      rows.appendChild(row);
    }
    xmlDoc.querySelector('template').remove();   // the template isn't needed in the output

    console.log(new XMLSerializer().serializeToString(rows));
  </script>
</body>
</html>

Cloning between documents

cloneNode keeps the copy in the same document. To copy a node into a different document, use importNode:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const source = new DOMParser().parseFromString(
      '<shop><product sku="T1"><name>Teapot</name></product></shop>', 'application/xml');
    const target = document.implementation.createDocument(null, 'wishlist');

    const imported = target.importNode(source.querySelector('product'), true);  // deep copy owned by target
    target.documentElement.appendChild(imported);

    console.log('owner is target?', imported.ownerDocument === target);
    console.log('source unchanged:', source.querySelectorAll('product').length);
    console.log(new XMLSerializer().serializeToString(target));
  </script>
</body>
</html>
cloneNode(true) importNode(node, true)
Called on The node The target document
Copy belongs to Same document The target document
Original Untouched Untouched

Tip: Cloning the whole document — xmlDoc.cloneNode(true) — is a quick way to keep an "undo" copy before a risky series of edits.

Test yourself

What does book.cloneNode(false) copy?

  1. Everything
  2. Only the element and its attributes, without children
  3. Only the children
  4. Nothing — it returns null

After const c = el.cloneNode(true), where is c?

  1. Right after el
  2. Replacing el
  3. Detached — not in the tree until inserted
  4. At the end of the root