Wrap multiple <p> elements in a <div> between <h3>
using jQuery, I would like to convert 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> IN:
<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 truly appreciated.
Thanks!
+2
2 answers
I use nextUntil to select all p elements after each h3 element and wrap it in a div using wrapAll before adding the h3 element and its wrapper to li , and then add it to ul . Mostly,
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
+7