包裹多个< p>元素进入< div>在< h3>之间

问题描述:

使用jQuery我想转换这个:

using jQuery I would like to transform this:

<h3>Question 1</h3>
<p>Answer 1 P1</p>
<p>Answer 1 P2</p>

<h3>Question 2</h3>
<p>Answer 2 P1</p>
<p>Answer 2 P2</p>
<p>Answer 2 P3</p>

进入:

<ul>
   <li>
       <h3>Question 1</h3>
       <div>
          <p>Answer 1 P1</p>
          <p>Answer 1 P2</p>
       </div>
    </li>
    <li>
       <h3>Question 2</h3>
       <div>
          <p>Answer 2 P1</p>
          <p>Answer 2 P2</p>
          <p>Answer 2 P3</p>
       </div>
    </li>
</ul>

任何建议将非常感激。

谢谢!

我正在使用 nextUntil ,以在每个 h3之后选择所有 p 元素元素,并使用 将其包装在 div 中在添加 h3 $ c之前,wrapAll $ c>元素,并在 li 中包装,然后将其附加到 ul 。基本上,

I'm using nextUntil to select all p elements after each h3 element and wrap it in a div using wrapAll, before adding the h3 element and wrapping that too in a li, then appending it to a ul. Basically,

var ul = $('<ul>').prependTo('body');

$('h3').each(function(){
    $(this).nextUntil('h3')
        .wrapAll('<div>').parent().add(this)
        .wrapAll('<li>').parent().appendTo(ul);
});

请参阅: http://www.jsfiddle.net/yijiang/SjDe2/1 简单演示