将父级添加到jquery中的一组节点

Sim*_*mon 2 html javascript jquery

所以我有以下结构:

  <h3>I.</h3>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>
    <ol>    
        <li>1.</li>
        <li>2.</li>
        <li>3.</li>
    </ol>
    <p>Some text</p>

    <h3>II.</h3>
            <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>

    <p>Some text</p>
    <ol>    
        <li>1.</li>
        <li>2.</li>
        <li>3.</li>
    </ol>
    <h3>III</h3> 
    etc
Run Code Online (Sandbox Code Playgroud)

我想以这种方式添加div元素:

  <h3>I.</h3>
   <div>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>
    <ol>    
        <li>1.</li>
        <li>2.</li>
        <li>3.</li>
    </ol>
    <p>Some text</p>
   </div>
    <h3>II.</h3>
   <div>
            <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>

    <p>Some text</p>
    <ol>    
        <li>1.</li>
        <li>2.</li>
        <li>3.</li>
    </ol>
  </div>
    <h3>III</h3> 
    etc
Run Code Online (Sandbox Code Playgroud)

我设法弄清楚如何将元素提升到下一个h3,但后来我被卡住了.

var elements = $("h3").nextUntil("h3");
            elements.wrapAll("<div>");
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 5

因为有多个h3元素需要循环遍历它们并nextUntil()在循环中使用:

$('h3').each(function() {
    $(this).nextUntil('h3').wrapAll('<div />');
});
Run Code Online (Sandbox Code Playgroud)

示例小提琴

  • 然后你需要使用直接兄弟选择器:`$('h2~h3')`:http://jsfiddle.net/srvyheyr/3/ (3认同)