每次h2后用div包装内容

dut*_*ler 1 jquery

任何人都可以给我一些想法如何用<div>每个<h2>标签包装任何内容并给它一个唯一的id,用jquery完成?

我试着这样做:

<h2>Test</h2>
 <div id="wrap_1"> // This is the wrapper im trying to add
   <p>Bla bla</p>
   <p>More Bla bla</p>
 </div>
<h2>Another test</h2>
 <div id="wrap_2"> // This is the wrapper im trying to add
   <p>Bla bla</p>
   <p>More Bla bla</p>
 </div>
Run Code Online (Sandbox Code Playgroud)

提前致谢

SLa*_*aks 6

像这样:

$('h2').each(function(index) { 
    $(this).nextUntil('h2').wrapAll('<div id="wrap' + index + '"></div>');
});
Run Code Online (Sandbox Code Playgroud)

演示