获取元素类型 (h1's) 之间的所有元素并包装在 div 中
我有以下结构:
<div class="wrapper">
<h1>Header 1</h1>
<h2>subtitle 1</h2>
<p>aaa</p>
<p>bbb</p>
<p>ccc</p>
<h2>subtitle2</h2>
<p>ddd</p>
<h1>Header 2</h1>
<h2>subtitle 3</h2>
<p>eee</p>
<p>fff</p>
</div>
我想选择每个H1和DIV中的所有H1和P元素,因此我最终得到了:
<div class="wrapper">
<div>
<h1>Header 1</h1>
<h2>subtitle 1</h2>
<p>aaa</p>
<p>bbb</p>
<p>ccc</p>
<h2>subtitle2</h2>
<p>ddd</p>
</div>
<div>
<h1>Header 2</h1>
<h2>subtitle 3</h2>
<p>eee</p>
<p>fff</p>
</div>
</div>
我尝试了以下各种事情,但是没有一个完美工作:
$( "h1" ).prevUntil( "h1" ).wrapAll( "<div></div>" );
I have the below structure:
<div class="wrapper">
<h1>Header 1</h1>
<h2>subtitle 1</h2>
<p>aaa</p>
<p>bbb</p>
<p>ccc</p>
<h2>subtitle2</h2>
<p>ddd</p>
<h1>Header 2</h1>
<h2>subtitle 3</h2>
<p>eee</p>
<p>fff</p>
</div>
I want to select all the h1 and p elements between each h1 and wrap in a div, so I end up with:
<div class="wrapper">
<div>
<h1>Header 1</h1>
<h2>subtitle 1</h2>
<p>aaa</p>
<p>bbb</p>
<p>ccc</p>
<h2>subtitle2</h2>
<p>ddd</p>
</div>
<div>
<h1>Header 2</h1>
<h2>subtitle 3</h2>
<p>eee</p>
<p>fff</p>
</div>
</div>
I've tried various things like the below, but none work perfectly:
$( "h1" ).prevUntil( "h1" ).wrapAll( "<div></div>" );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
.prevUntil
将反转 Dom 节点遍历,请使用.nextUntil
代替。为了匹配最终输出,脚本如下:
.prevUntil
will inverse the Dom node traversing, use.nextUntil
instead.as to match the end-up output, the script is as follows:
我想出了这个解决方案,它获取所有子级,然后如果它是 h1 标签,它将创建一个新的 div 并将 H1 和其他子级移动到其中
I came up with this solution where it gets all the children and then if its a h1 tag it will create a new div and move H1 and other children into it