Wrap everything from certain div to certain div

advertisements

I have a blog style layout in a cms so there are multiple instances of these divs.

This is the structure:

<div class="sfpostContent">
     <p>Some text</p>
     random text
     <p>Some text</p>
     <div class="sfpostsList-img">
         <img src="myimage.jpg"/>
     </div>
</div>
<div class="sfpostContent">
     <p>Some text</p>
     random text
     <p>Some text</p>
     <div class="sfpostsList-img">
         <img src="myimage.jpg"/>
     </div>
</div>

I want it to look like this:

    <div class="sfpostContent">
         <div class="sfpostsList-detail">
             <p>Some text</p>
             random text
             <p>Some text</p>
         </div>
         <div class="sfpostsList-img">
             <img src="myimage.jpg"/>
         </div>
    </div>
   <div class="sfpostContent">
         <div class="sfpostsList-detail">
             <p>Some text</p>
             random text
             <p>Some text</p>
         </div>
         <div class="sfpostsList-img">
             <img src="myimage.jpg"/>
         </div>
    </div>

Please note: I am already wrapping my image in sfpostsList-img via jquery

I want everything from sfpostContent to the start of sfpostsList-img wrapped in sfpostsList-detail

It is an fck editor so there's no telling what people will put in there.


I'm sure there is a more elegant way to do it, but quick and dirty:

$('.sfpostContent').each(function() {
      var list_img = $(this).find('.sfpostsList-img');
      var list_img_html = list_img[0].outerHTML;
      list_img.remove();
      $(this).html('<div class="sfpostsList-detail">' + $(this).html() + '</div>' + list_img_html);
});