I have the following HTML:
<div class="accordion">
<h3>My title</h3>
<div>My content</div>
<h3>My title</h3>
<div>My content</div>
<h3>My title</h3>
<div>My content</div>
</div>
What I need to do via jQuery is wrap each of the h3's and div's in another div class="myDiv", so the final output would look like:
<div class="accordion">
<div class="myDiv">
<h3>My title</h3>
<div>My content</div>
</div>
<div开发者_Python百科 class="myDiv">
<h3>My title</h3>
<div>My content</div>
</div>
<div class="myDiv">
<h3>My title</h3>
<div>My content</div>
</div>
</div>
How would I do this with jquery?
Try this:
$("h3").each(function(){
$(this).next("div").andSelf().wrapAll("<div class='myDiv'></div>");
});
http://jsfiddle.net/BSQpf/
Something like this should do it:
$('.accordion h3').each(function() {
$(this).nextUntil('h3').andSelf().wrapAll('<div class="myDiv"/>');
});
jsFiddle example
See the API:
nextUntil
andSelf
wrapAll
精彩评论