Jose
Jose

Reputation: 21

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

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>

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!

Upvotes: 2

Views: 1243

Answers (2)

Yi Jiang
Yi Jiang

Reputation: 50125

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

Upvotes: 7

Tx3
Tx3

Reputation: 6916

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

Upvotes: 0

Related Questions