How can I implement jQuery.wrapInner () function in plain javascript?

I bookmark in simple javascript and I would like to wrap all the contents of the original body of the site in a div so that I can separate this content from what I am adding ...

In my scenario, I am trying to add fixed vertical navigation of full width, but I would like to add an addition to the rest of the content.

Thank!

+3
source share
2 answers
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 turn them into a function by passing in the parent element and possibly the desired container as the name of the node or 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");
+3
source

I assume it could be:

var dv = document.createElement('div');
var body = document.getElementsByTagName('body')[0];
var elements = body.childNodes;
for(var i = 0; i < elements.length; i++)
{
     dv.appendChild(elements[i]);
}
body.appendChild(dv);
0
source

All Articles