Search code examples
javascriptjqueryselectorsiblingswrapall

How can I wrap each element and all its siblings before the next occurrence of the same element?


I've got some markup that's similar to the following:

<h3>A Heading</h3>
<p>Here is a paragraph.</p>

<ul>
  <li>First</li>
  <li>Second</li>
</ul>

<blockquote>Here's some other block-level element</blockquote>

<h3>The Wrapping Should Stop Before This Heading, but a Second One Should Begin</h3>
<ol>
  <li>First</li>
  <li>Second</li>
</ol>

<p>Notice the varying block-level elements? It probably doesn't make any difference.</p>

I want to wrap each h3 and everything up to, but not including, the next h3 in a single div.

The result should be:

<div>
  <h3>A Heading</h3>
  <p>Here is a paragraph.</p>

  <ul>
    <li>First</li>
    <li>Second</li>
  </ul>

  <blockquote>Here's some other block-level element</blockquote>
</div>

<div>
  <h3>The Wrapping Should Stop Before This Heading, but a Second One Should Begin</h3>
  <ol>
    <li>First</li>
    <li>Second</li>
  </ol>

  <p>Notice the varying block-level elements? It probably doesn't make any difference.</p>
</div>

I've found similar questions like this one. It uses a combination of .nextUntil() and .andSelf() (or .addBack() once my edit is approved), but this would wrap the h3s and the content between in separate divs.


Solution

  • It seems .wrapAll() was the missing link.

    $('h3').nextUntil('h3').addBack().wrapAll('<div>');