Alex Rivera | Logout

Insert <div> for every 5 elements using Javascript

Asked 2011-08-30T19:05:43.457
9

I have a simple list of images that is being controlled via a CMS (ExpressionEngine). Like this:

<div class="wrapper">
    <a href="#"><img src="#" /></a>
    <a href="#"><img src="#" /></a>
    <a href="#"><img src="#" /></a>
    <a href="#"><img src="#" /></a>
    <a href="#"><img src="#" /></a>
    <a href="#"><img src="#" /></a>
    <a href="#"><img src="#" /></a>
    <a href="#"><img src="#" /></a>
</div>

What I want to do is for every 5 images, wrap them in a div with a class of "slide." To look like this:

<div class="wrapper">
    <div class="slide">
      <a href="#"><img src="#" /></a>
      <a href="#"><img src="#" /></a>
      <a href="#"><img src="#" /></a>
      <a href="#"><img src="#" /></a>
      <a href="#"><img src="#" /></a>
    </div>
    <div class="slide">
      <a href="#"><img src="#" /></a>
      <a href="#"><img src="#" /></a>
      <a href="#"><img src="#" /></a>
    </div>
</div>

The reason I am not manually coding the "" in is because of a jQuery content slider that I am using which requires every 5 images to be wrapped inside a slide div.

I'm not sure how what the code in ExpressionEngine would be to do this, but I figure it might just be easier to use Javascript to wrap every 5 images with the div. And to just have ExpressionEngine output the different images all at once.

Any help?

Edit
Report

1 Answer

0

Use slice() to select the element subset then wrapAll() to wrap the div around them. Here's a function that does that.

var wrapEveryN = function(n, elements, wrapper) {
   for (var i=0; i< elements.length; i+=n) {
       elements.slice(i,i+n).wrapAll(wrapper);
   }
}

wrapEveryN( 5, $(".wrapper a"), '<div class="slide"></div>' );

Demo: http://jsfiddle.net/C5cHC/

Note that the second parameter of slice may go out of bounds, but jQuery seems to handle this automatically.

answered 2011-08-30T19:21:04.947

Your Answer