Ana Sampaio Ana Sampaio - 5 months ago 9x
Javascript Question

How to wrap elements inside of body dynamically

I need to wrap the elements inside of the

<div id="wrap">
dynamically, using jQuery/JavaScript. The final result has to be:

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

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

Thank you!


Use .wrapAll() method, as below:

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

JSBin Demo