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?
Example: http://jsfiddle.net/TK6ay/1/
$('.heading').each(function(){
$(this).nextUntil('.heading').andSelf().wrapAll('<div class="section"/>');
});
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With