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.
function deepCloneDom(node) {
// returns a new, independent copy of node and its subtree
}
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)
nodeType — element = 1, text = 3, comment = 8. Each gets its own factory: createElement, createTextNode, createComment.element.attributes and setAttribute(name, value) on the clone.childNodes — not children, so text and comment nodes come along too; append each cloned child.