Question

HTML snippet:

<h1>Heading</h1>
<p>paragraph paragraph paragraph</p>
<h2>Heading</h2>
<p>paragraph paragraph paragraph</p>

The snippet above is equal to:

<section>
  <h1>Heading</h1>
  <p>paragraph paragraph paragraph</p>
  <section>
    <h2>Heading</h2>
    <p>paragraph paragraph paragraph</p>
  </section>
</section>

As mentioned here.

Now I want to do this by jQuery from the first snippet. Is there already an API for this?

Was it helpful?

Solution

Demo : http://jsfiddle.net/abdennour/LX2YX/

$('h2').next('p').andSelf().wrapAll('<section />');

$('h1').next().andSelf().next().andSelf().wrapAll('<section />');

You can see browser inspector to check your DOM tree :

enter image description here

OTHER TIPS

Another approach which is easy :

$('h1,p,h2').wrapAll('<section />');
$('h2,p:eq(1)').wrapAll('<section />');

Demo : http://jsfiddle.net/abdennour/LX2YX/1/

NOTE : the selector 'p:eq(1)' means the second <p> in your page

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top