3

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>
double-beep
  • 5,031
  • 17
  • 33
  • 41
geemeetheway
  • 125
  • 1
  • 10

1 Answers1

7

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)

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134