开发者

Wrapping a div around the document body contents

I am trying to dynamically wrap the contents of a document's body tag in a DIV. So far, I have used the following code:

document.body.innerHTML = '<div id="wrap">' + document.body.innerHTML + '开发者_JS百科</div>';

This works, but has the unwanted side effect that other scripts on the same page stop working (I assume because changing innerHTML renders any object references they may have held useless).

What would be the best/most efficient way to achieve this and keep the references intact, using pure JavaScript, or the Prototype framework?


You would do something like:

var div = document.createElement("div");
div.id = "wrap";

// Move the body's children into this wrapper
while (document.body.firstChild)
{
    div.appendChild(document.body.firstChild);
}

// Append the wrapper to the body
document.body.appendChild(div);


you could try this? (untested)

var newDiv = document.createElement('div')
newDiv.setAttribute('id','wrap');
var bodyChildren = document.body.childNodes;
for(var i=0;i<bodyChildren.length;i++){
  newDiv.append(bodyChildren[i]);
}
document.body.appendChild(newDiv);

Not sure about prototype, but in jQuery you can do this

$('body').wrap('<div id="wrap"></div>');


Maybe something like this:

var body = document.body;
var div = document.createElement('div');
div.className = 'wrapper';

div.innerHTML = body.innerHTML;
body.innerHTML = div.outerHTML;


$('#iframe').contents().find('body').wrap('<div class=body></div>');
$('#iframe').contents().find('body').replaceWith(function() {return this.innerHTML});
$('#iframe').contents().find('.body').wrap('<body></body>');

this lines are going to wrap a div inside body element tag. First, it will wrap the body tag, then remove the body tag and append its all contents to the body div and the 3rd line will wrap this div again with the body tag.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜