开发者

Wrap Multiple <p> elements into <div> between <h3>

using jQuery I would like to transform this:

<h3>Question 1</h3>
<p>Answer 1 开发者_JS百科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>

Into:

<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>

Any suggestion would be really appreciated.

Thank you!


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);
});

See: http://www.jsfiddle.net/yijiang/SjDe2/1 for a simple demo


Interesting! I'm eagerly waiting for different kind of solutions.

In theory: I would use selector $('h3, p').each(logic) to go through all those items and when I encounter tag h3 I would create li, h3 and div and when I would encounter p I would add p to the div

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜