Search code examples
javascripthtmlprototypejs

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


Solution

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