Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert <div> for every 5 elements using Javascript

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?

like image 964
cusejuice Avatar asked Aug 30 '11 19:08

cusejuice


2 Answers

Here's one way:

Example: http://jsfiddle.net/T6tu4/

$('div.wrapper > a').each(function(i) {
    if( i % 5 == 0 ) {
        $(this).nextAll().andSelf().slice(0,5).wrapAll('<div class="slide"></div>');
    }
});

Here's another way:

Example: http://jsfiddle.net/T6tu4/1/

var a = $('div.wrapper > a');

for( var i = 0; i < a.length; i+=5 ) {
    a.slice(i, i+5).wrapAll('<div class="slide"></div>');
}
like image 99
user113716 Avatar answered Oct 27 '22 23:10

user113716


You can just create a div for every fith element and move the links into them using the append method:

var wrapper = $('.wrapper');
var div;
$('a', wrapper).each(function(i,e){
    if (i % 5 == 0) div = $('<div/>').addClass('slide').appendTo(wrapper);
    div.append(e);
});

Demo: http://jsfiddle.net/Guffa/ybrxu/

like image 45
Guffa Avatar answered Oct 27 '22 22:10

Guffa