admin管理员组

文章数量:1323225

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!

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!

Share Improve this question asked Feb 16, 2014 at 22:23 whitcrrdwhitcrrd 691 silver badge3 bronze badges 2
  • Why is it so important to not use jQuery? It's a powerful tool that will simply do exactly what you require? – Patrick Eaton Commented Feb 16, 2014 at 22:27
  • 1 @PatrickEaton: jQuery is very often just too much code to load for simple problems, especially if you're not supporting IE6 and 7. – cookie monster Commented Feb 16, 2014 at 22:41
Add a ment  | 

2 Answers 2

Reset to default 8
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");

I guess 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);

本文标签: How can I implement jQuery39s wrapInner() function in plain javascriptStack Overflow