Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 794
whitcrrd Avatar asked Feb 16 '14 22:02

whitcrrd


1 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 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");
like image 179
cookie monster Avatar answered Oct 23 '22 19:10

cookie monster