Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to generate wrapping DIVs once page is loaded

We are working with a CMS that generates the following HTML:

<h3 class="heading">Heading 1</h3>
  <div>Content</div>
  <div>More content</div>
  <div>Even more content</div>
<h3 class="heading">Heading 2</h3>
  <div>Some content</div>
  <div>Some more content</div>
<h3 class="heading">Heading 3</h3>
  <div>Other content</div>

Unfortunately we can't easily change this structure but we want to add the following divs to be used in an accordion style dynamic layout:

<div class="section">
  <h3 class="heading">Heading 1</h3>
    <div>Content</div>
    <div>More content</div>
    <div>Even more content</div>
</div>
<div class="section">
  <h3 class="heading">Heading 2</h3>
    <div>Some content</div>
    <div>Some more content</div>
</div>
<div class="section">
  <h3 class="heading">Heading 3</h3>
    <div>Other content</div>
</div>

I was wondering how to add wrapping divs once the page is loaded using jQuery.

The code would have to walk the DOM, identify h3.heading and then create a wrapping parent div around the heading and all the following divs.

Or is there a simpler way of achieving this?

like image 365
BaronGrivet Avatar asked Apr 02 '12 22:04

BaronGrivet


2 Answers

Example: http://jsfiddle.net/TK6ay/1/

$('.heading').each(function(){
    $(this).nextUntil('.heading').andSelf().wrapAll('<div class="section"/>');
});
like image 159
elclanrs Avatar answered Oct 03 '22 07:10

elclanrs


This should be exactly what you need:

(function($) {
    $('h3').each(function() {
       $(this).nextUntil('h3').andSelf().wrapAll('<div class="section"/>');
    });
})(jQuery);

Here's a working example: http://jsfiddle.net/SFVQP/

like image 45
Eli Sand Avatar answered Oct 03 '22 08:10

Eli Sand