Skip to content

Instantly share code, notes, and snippets.

@developit
Created September 29, 2020 18:59
Show Gist options
  • Save developit/45c85e9be01e8c3f1a0ec073d600d01e to your computer and use it in GitHub Desktop.
Save developit/45c85e9be01e8c3f1a0ec073d600d01e to your computer and use it in GitHub Desktop.
/**
* cloneNode(true), but also clones shadow roots.
* @param {Element}
* @param {ShadowRoot[]} [shadowRoots] Any closed shadow roots passed here will be included.
*/
function cloneWithShadowRoots(node, shadowRoots) {
function walk(node, clone) {
let shadow = node.shadowRoot || shadowRoots.find(r => r.host === node);
if (shadow) {
clone.attachShadow({ mode: shadow.mode }).append(...[].map.call(shadow.childNodes, c => c.cloneNode(true)));
}
for (let i=0; i<node.children.length; i++) walk(node.children[i], clone.children[i]);
}
const clone = node.cloneNode(true);
walk(node, clone);
return clone;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment