1

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.

Peter Featherstone
  • 7,835
  • 4
  • 32
  • 64

1 Answers1

3

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

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Great solution, my only question is how intensive this is to use due to the asterisk and the need to go through all body elements, although I suspect that using the > limits this to only top level elements that it should be ok? – Peter Featherstone Jul 04 '16 at 14:51
  • That is a concern, but given the HTML structure in your OP there is unfortunately no alternative. If you could manually add a class to all the required elements it would improve performance, but I'm guessing if you could edit the HTML you wouldn't need to do this in the first place :) Performance with this should be fine though. You're correct that the `>` operator is restricting the selector to children of `body` only. – Rory McCrossan Jul 04 '16 at 14:53
  • As it is only used once on page load and has no need to re-run on page clicks or with interactive elements etc. I think the performance will be fine. You're right, if I had access to the HTML this would be a much easier fix! Thanks again for the help, I had been tearing my hair out over something that in the end was so simple and elegant :-) – Peter Featherstone Jul 04 '16 at 14:58