daveredfern
daveredfern

Reputation: 1255

Wrap several elements for accordion in jquery

I currently have the following html:

<h3 />
<p />
<p />
<ul />
<ol />

<h3 />
<p />
<p />
<ul />
<ol />

<h3 />
<p />
<p />
<ul />
<ol />

I'd like to create an accordion but for this I need the following:

<h3 />
<div>
     <p />
     <p />
     <ul />
     <ol />
</div>

<h3 />
<div>
     <p />
     <p />
     <ul />
     <ol />
</div>

I have tried the following, but it doesn't work:

$('.page2 .articleText p, .page2 .articleText ul').after('<div class="accordion">');
$('.page2 .articleText h4:not(:first)').before('</div>');

Any help is much appreciated.

Thanks!

Upvotes: 3

Views: 382

Answers (2)

Nick Craver
Nick Craver

Reputation: 630379

You can use .nextUntil() and .wrapAll() to select and wrap each section, like this:

$("h3").each(function() {
    $(this).nextUntil("h3").wrapAll("<div />");
});​

You can see a working demo here

Upvotes: 1

Juraj Blahunka
Juraj Blahunka

Reputation: 18523

Here's a quick'n'dirty solution for wrapping a group of elements into one div:

$(function(){
    var h  = $('h3');
    var p1 = $('h3 + p');
    var p2 = $('h3 + p + p');
    var ul = $('h3 + p + p + ul');
    var ol = $('h3 + p + p + ul + ol');

    h.each(function (i) {
        var group = $(p1[i]).add(p2[i]).add(ul[i]).add(ol[i]);
        var div = $('<div />').append(group);
        $(h[i]).after(div);
    });
});    

I believe if you provided some hooks, the code would be much simpler :)

Upvotes: 0

Related Questions