Peter Featherstone Peter Featherstone - 5 months ago 17
jQuery Question

wrapInner() of body until a specified element

Using the below HTML:

<body>
<h1>Foo</h1>
<div>a</div>
<div>b</div>
<h4>Bar</h4>
<div>c</div>
<div id="wrap-until"></div>
</body>


I can wrap the whole of the body section easily using
$('body').wrapInner('<div class="content"></div>');
but how can I wrap the body content up until my wrap-until div element, so it looks like:

<body>
<div class="content">
<h1>Foo</h1>
<div>a</div>
<div>b</div>
<h4>Bar</h4>
<div>c</div>
</div>
<div id="wrap-until"></div>
</body>


Note: The content inside the body will always be different but the #wrap-until element will always be available.

Answer

You can grab all the required elements and use not() to exclude the wrap-until element then wrapAll(), like this:

$('body > *').not('#wrap-until').wrapAll('<div class="content"></div>');

Working example

Comments