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

时间:2013-09-08 05:01:37

标签: javascript jquery selector siblings 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>

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

我发现了像this one这样的类似问题。在我的编辑获得批准后,它会使用.nextUntil().andSelf()(或.addBack())的组合,但这会将h3之间的内容分开 div s。

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:3)

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

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

Fiddle