Wrapping a div around the document body contents

Skybly picture Skybly · Oct 16, 2009 · Viewed 9.3k times · Source

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?

Answer

Anthony Mills picture Anthony Mills · Oct 16, 2009

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