views:

315

answers:

2

Hello! 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 + '</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?

Thanks in advance!

+1  A: 

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>');
scunliffe
This is exactly what I was going to say, only difference I would have mentioned, use the Prototype DOM Builder: http://prototypejs.org/2007/5/12/dom-builder
robertc
Thank you! (There's a wrap method in prototype that I experimented with, but I only managed to wrap the div around the outside of the body, not the inside).
Skybly
+1  A: 

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);
Anthony Mills
That worked flawlessly - thank you!
Skybly
The problem is, that all attached JavaScript events get lost when you reassign html-content this way.
acme
Or at least the ones that are assigned within the code (I guess the onlick-handlers still remain intact).
acme
Strange. By doing it this way, most DOM objects are completely unaffected, and even the body's children only have their position altered. Attached events should be completely unchanged. Not like if you did something like `document.body.innerHTML = "<div id='wrap'>" + document.body.innerHTML + "</div>";` ! :)
Anthony Mills
worked great. thanks!
Jabes88