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

问题描述 投票:4回答:2

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

<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())的组合,但这将包装h3s和内容之间的单独divs。

javascript jquery selector siblings wrapall
2个回答
4
投票

似乎.wrapAll()是缺失的环节。

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

3
投票

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

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

Fiddle

© www.soinside.com 2019 - 2024. All rights reserved.