Search code examples
jqueryhtmloutline

How can I wrap implicit section in HTML 5 by jQuery?


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?


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