简体   繁体   中英

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 h3 s and the content between in separate div s.

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

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

You need the :first selector otherwise you will wrap all the content not just the first h3 to 2nd h3

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

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM