Search code examples
javascriptjqueryhtmlwrapall

How to wrap h1 and follow content in div?


I need to know how to wrap h1 and follow content in div. This is the original structure:

<h1>Title #1</h1>
<p>Text</p>
<p>Text</p>

<h1>Title #2</h1>
<p>Text</p>
<p>Text</p>
<p>Text</p>

<h1>Title #3</h1>
<p>Text</p>

This is the result I want to get :

<div>
  <h1>Title #1</h1>
  <p>Text</p>
  <p>Text</p>
</div>

<div>
  <h1>Title #2</h1>
  <p>Text</p>
  <p>Text</p>
  <p>Text</p>
</div>

<div>
  <h1>Title #3</h1>
  <p>Text</p>
</div>


Solution

  • Try using wrapAll and group the h1 and all p tags

    $(function () {
        $('h1').each(function () {
            $(this).nextUntil('h1').add(this).wrapAll('<div />');
        });
    });
    

    DEMO: http://jsfiddle.net/zPafK/

    or http://jsfiddle.net/zPafK/2/ (added some styles)