Ana Sampaio
Ana Sampaio

Reputation: 351

How to wrap elements inside of body dynamically

I need to wrap the elements inside of the body by <div id="wrap"> dynamically, using jQuery/JavaScript. The final result has to be:

<body>
    <div id="wrap">
        <!-- open div #wrap here -->
        <div id="nav">
            <ul>
                <li><a href="#">Menu 1</a></li>
                <li><a href="#">Menu 2</a></li>
            </ul>
        </div>
        <div id="main">....</div>
    </div>
    <!-- close div #wrap here, before close body tag -->
</body>

Should I create the div and after add the content that already exists inside body? How can I do it?

Thank you!

Upvotes: 0

Views: 147

Answers (4)

Improvement_Needed
Improvement_Needed

Reputation: 73

wrapAll should produce several div tags. I would have used wrapInner instead.

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

Upvotes: 0

Hashem Qolami
Hashem Qolami

Reputation: 99494

Use .wrapAll() method, as below:

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

JSBin Demo

Upvotes: 1

faino
faino

Reputation: 3224

First you would want to grab the current HTML and store it in a variable, then the use of the .html()method will do wonders:

$(function(){
    var bod = $("body"), current_html = bod.html();
    bod.html("<div id=\"wrap\">" + current_html + "</div>");
});

Upvotes: 3

Mark Cidade
Mark Cidade

Reputation: 99957

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

Upvotes: 0

Related Questions