How can I implement jQuery's .wrapInner() function in plain javascript?
dom, html, javascript, jquery
Solution
var div = document.createElement("div");
while(document.body.firstChild)
div.appendChild(document.body.firstChild);
document.body.appendChild(div);
Or
var div = document.body.appendChild(document.createElement("div"));
while(document.body.firstChild !== div)
div.appendChild(document.body.firstChild);
And of course you can make them into a function, by passing the parent and optionally the desired container as a node name or a node.
function wrapInner(parent, wrapper) {
if (typeof wrapper === "string")
wrapper = document.createElement(wrapper);
var div = parent.appendChild(wrapper);
while(parent.firstChild !== wrapper)
wrapper.appendChild(parent.firstChild);
}
then
wrapInner(document.body, "div");
Problem
I'm making a bookmark in plain javascript, and I'd like to wrap all of the site's original body content in a div, so that I can separate that content from what I am adding... In my scenario, I'm trying to add a fixed, vertical, full-width nav, but I'd like to add padding to the rest of the content. Thanks!