如何在下一次出现相同元素之前包装每个元素及其所有同级元素?

Cur*_*ell 5 javascript jquery siblings selector wrapall

我有一些类似于以下内容的标记:

<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>
Run Code Online (Sandbox Code Playgroud)

我想将所有h3内容(但不包括下一个)包装h3在一个div.

结果应该是:

<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>
Run Code Online (Sandbox Code Playgroud)

我发现了类似的问题.nextUntil()它使用和的组合.andSelf()(或者.addBack()一旦我的编辑被批准),但这会将h3s 和之间的内容包装在单独的 divs 中。

Cur*_*ell 4

看来.wrapAll()是缺少的环节。

$('h3').nextUntil('h3').addBack().wrapAll('<div>');
Run Code Online (Sandbox Code Playgroud)