Ana Sampaio Ana Sampaio - 7 months ago 25
Javascript Question

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!

Answer

Use .wrapAll() method, as below:

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

JSBin Demo