views:

71

answers:

2

In jQuery how would I go about wrapping a repeatable set of elements with a div?

For example I have:
img
h4
p
img
h4
p
img
h4
p
I need to wrap each img, h4, p set with a div class="container". So it will look like:
<div> class="container"> img h4 p </div>
<div> class="container"> img h4 p </div>
<div> class="container"> img h4 p </div>

Any ideas on how I can achieve this as its driving me nuts! I keep getting nested div.containers! Thanks!

+1  A: 

You can do something like this:

var elems = $("#content").find("img, h4, p");
for(var i = 0; i < elems.length; i+=3) {
  elems.slice(i, i+3).wrapAll("<div class='container'></div>");
}

This works by selecting the container these elements are in and grabbing this specific types, if the elements you want are everything, you can replace .find(selector) with .children(), in this case I used this for the parent element:

<div id="container"></div>

You can see a working demo here

Nick Craver
+1, you win <sigh>
karim79
@karim - Had the slight advantage of answering this a few times ;) http://stackoverflow.com/questions/2485479/jquery-wrap-code-after-x-number-of-elements
Nick Craver
haha sorry I didnt even see that previous question! Thanks heaps man and thanks for showing me the jsfiddle site thats awesome.
Globalz
@Globalz - Make sure to accept answers via the check-mark beside the one that helped, makes your questions much more appealing to would-be answerers :)
Nick Craver
Your too helpful! LOL Thanks dude I gave you the green tick!
Globalz
A: 

Your example is pretty simple, so this will work:

$("h4").each(function () {
  $(this).prev().andSelf().next().andSelf().wrapAll("<div class='container'/>");
});

demo here

bcherry
That's a **lot** of traversing for doing something that can be much faster, `$("img").each(function() { $(this).nextUntil("img").andSelf().wrapAll("<div class='container'></div>"); });` for example.
Nick Craver
Didn't know about `nextUntil` (can you tell I don't do DOM traversal in jQuery much?). Great improvement :)
bcherry