Created
April 28, 2016 09:27
-
-
Save dmail/b9b292b72d612c29615a7f15595a52a9 to your computer and use it in GitHub Desktop.
Sort of node.cloneNode(true) on descendant only
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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