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

馋奶兔 提交于 2019-12-11 04:02:16

问题


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!


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/4794705/wrap-multiple-p-elements-into-div-between-h3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!