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&g开发者_运维问答t;
<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!
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
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 :)
精彩评论