Skip to content

Instantly share code, notes, and snippets.

@Daniel-Hug
Last active December 30, 2016 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daniel-Hug/36d26a391ff443941940ced9c4b04b3f to your computer and use it in GitHub Desktop.
Save Daniel-Hug/36d26a391ff443941940ced9c4b04b3f to your computer and use it in GitHub Desktop.
JS function: wrap multiple nodes with a wrapper element
// 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