4

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

<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>

我想将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>

我发现了类似的问题这样一个。它使用.nextUntil()and的组合.andSelf()(或者.addBack()一旦我的编辑被批准),但这会将s 和单独h3的 s之间的内容包装起来。 div

4

2 回答 2

4

似乎.wrapAll()是缺少的链接。

$('h3').nextUntil('h3').addBack().wrapAll('<div>');
于 2013-09-08T05:07:06.250 回答
3

您需要:first选择器,否则您将包装所有内容,而不仅仅是第一个h3到第二个h3

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

小提琴

于 2013-09-08T05:09:58.203 回答