Last active
December 30, 2016 07:47
-
-
Save Daniel-Hug/36d26a391ff443941940ced9c4b04b3f to your computer and use it in GitHub Desktop.
JS function: wrap multiple nodes with a wrapper element
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
// Wrap wrapper around nodes | |
// Just pass a collection of nodes, and a wrapper element | |
function wrapAll(nodes, wrapper) { | |
// Cache the current parent and previous sibling of the first node. | |
var parent = nodes[0].parentNode; | |
var previousSibling = nodes[0].previousSibling; | |
// Place each node in wrapper. | |
// - If nodes is an array, we must increment the index we grab from | |
// after each loop. | |
// - If nodes is a NodeList, each node is automatically removed from | |
// the NodeList when it is removed from its parent with appendChild. | |
for (var i = 0; nodes.length - i; wrapper.firstChild === nodes[0] && i++) { | |
wrapper.appendChild(nodes[i]); | |
} | |
// Place the wrapper just after the cached previousSibling, | |
// or if that is null, just before the first child. | |
var nextSibling = previousSibling ? previousSibling.nextSibling : parent.firstChild; | |
parent.insertBefore(wrapper, nextSibling); | |
return wrapper; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment