Skip to content

Instantly share code, notes, and snippets.

@dmail
Created April 28, 2016 09:27
Show Gist options
  • Save dmail/b9b292b72d612c29615a7f15595a52a9 to your computer and use it in GitHub Desktop.
Save dmail/b9b292b72d612c29615a7f15595a52a9 to your computer and use it in GitHub Desktop.
Sort of node.cloneNode(true) on descendant only
// will return a cloned version of rootNode descendants
// in itself this function is useless but it can be modified to add custom cloning behaviour
function cloneNodeDeep(rootNode) {
var node = rootNode;
var rootClone = document.createDocumentFragment();
var nodeClone = rootClone;
while (node) {
var nextNode = null;
var firstChild = node.firstChild;
if (firstChild) {
nextNode = firstChild;
} else {
while (node !== rootNode) {
var nextSibling = node.nextSibling;
if (nextSibling) {
nextNode = nextSibling;
break;
}
node = node.parentNode;
nodeClone = nodeClone.parentNode;
}
}
if (nextNode) {
var nextNodeClone = nextNode.cloneNode(false);
if (firstChild) {
nodeClone.appendChild(nextNodeClone);
} else { // nextsibling, must append in parent
nodeClone.parentNode.appendChild(nextNodeClone);
}
nodeClone = nextNodeClone;
node = nextNode;
} else {
node = null;
}
}
return rootClone;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment