Deep Clone DOMLoading saved progress…

Deep Clone DOM

The browser gives you node.cloneNode(true) to deep-copy a DOM subtree — but implementing it yourself is a great exercise in recursion over a heterogeneous tree. A DOM node isn't just elements: it's elements (with attributes), text nodes, and comments, and a clone has to reproduce each kind faithfully so the copy is a fully independent tree. Change the clone, and the original mustn't budge.

Implement deepCloneDom(node) without cloneNode. Recreate the node by type — element (tag + attributes + cloned children), text, or comment — recursing into children so the whole subtree is duplicated.

Signature

function deepCloneDom(node) {
  // returns a new, independent copy of node and its subtree
}

Examples

const clone = deepCloneDom(el('<p>before<b>bold</b>after</p>'));
clone.outerHTML; // '<p>before<b>bold</b>after</p>'
clone !== original;                 // true
clone.querySelector('b') !== original.querySelector('b'); // true (deep)

Notes

  • Branch on nodeType — element = 1, text = 3, comment = 8. Each gets its own factory: createElement, createTextNode, createComment.
  • Copy attributes — iterate element.attributes and setAttribute(name, value) on the clone.
  • Recurse over childNodes — not children, so text and comment nodes come along too; append each cloned child.
  • Independence — every node in the result is freshly created, so mutating the clone can't reach the original.
Loading editor…