Search code examples
jqueryhtmlsections

jQuery automatic html divs


I need to add sections to a content page with jQuery.

I need to do it this way so my client can use a text editor without worrying about html.

So this:

<h2></h2>
<p></p>
<p></p>
<h2></h2>
<p></p>

Would become

<div class="section">
    <h2></h2>
    <p></p>
    <p></p>
</div>
<div class="section">
    <h2></h2>
    <p></p>
</div>

So far I have this jQuery

jQuery(function($){
var i = 0;

var headers = $('#post-2618 h2');

headers.each(function(){
    i++;

    if(i == 1){
        $(this).before('<div class="section">');
    }else{
        $(this).before('</div><div class="section">');
    }
});

$('#post-2618').after('</div>');

});

But that makes the code look like this

<div class="section"></div>
<h2></h2>
<p></p>
<p></p>
<div class="section"></div>
<h2></h2>
<p></p>

I think the browser corrects the html before the end of the script.

Is there an easy way around this?

Thank you for your help!

Jordan


Solution

  • .before and .after adds dom elements not text.

    what you should do is the folowing:

        $("h2").each(function() {
          //create section dom element
          section = $("<div class='section' />");
    
          //find all p tags until next h2  and wrap all in the section dom element
          $(this).nextUntil("h2").wrapAll(section);
          //find newly appended .section element and grab the h2
          $(this).prependTo($(this).next(".section"));   
       });
    

    http://jsfiddle.net/81ncLnnL/1/