Take n items from the collection.

I am sure that this is not a specific jQuery question, but I use it to accomplish my task, so I will describe what I need in the context of jQuery and HTML. I have an HTML page with divs that are generated by the server. They look like

<div class="image"><img src="image1.png" /></div>
<div class="image"><img src="image2.png" /></div>
...
<div class="image"><img src="imagen.png" /></div>

The divs counter is variable and can be, for example, 40-50. I take their collection with something like this: images = jQuery('.image'); Now I need to take every 9 divs from the collection and put them in a newly created container, for example, as follows:

<div class="container1">
<div class="image"><img src="image1.png" /></div>
<div class="image"><img src="image2.png" /></div>
<div class="image"><img src="image3.png" /></div>
...
<div class="image"><img src="image9.png" /></div>
</div>

Then I need to take the following 9 elements and put them in a similar newly created div, for example:

<div class="container2">
<div class="image"><img src="image10.png" /></div>
<div class="image"><img src="image11.png" /></div>
<div class="image"><img src="image12.png" /></div>
...
<div class="image"><img src="image18.png" /></div>
</div>

. , , 9 . , , 9. , 9 . .

+3
4

FIX!

.. . patrick dw. , .

var images = jQuery('.image');
for(i = 0; i < images.length / 9; i++) {
 jQuery('<div />', {
   id: 'conainter_' + i,
   html: images.slice(i*9, i*9+9)
 }).appendTo('body');
}

;)

+3

, .

: http://jsfiddle.net/kQ4Vp/ ( , + (i / 9) , .)

var $images = $('.image'); // get all the elements with the class "image"
var i = 0; // Start counter at 0. It will increment by 9: 0, 9, 18, etc.

 // Run a loop while "i" is less than the total number of images
while ( i < $images.length ) {

     // Create a new div, giving it a class "container0" "container1" etc.
    $('<div>', {'class':'container' +  (i / 9)})

            // Take a slice of the images from the current "i" thru "i + 9"
            //  so, 0-9, 9-18, 18-27, etc. and append them to the new div
        .append( $images.slice(i, i + 9) )

        .appendTo( 'body' );  // Append the new div to the body (or wherever)

    i += 9; // Increment "i" by 9
}

EDIT: while do/while. , .

+2

, slice end :

var pars = $('p');
pars.slice(0,4);
// do something with it, such as append()
pars.end().slice(5,9);
// do something with this slice, etc

pars.slice , .

+1

, , divs DOM.

var $images = $(".image"),
    len = 9;

for (var x = 0, y = 1; x < $images.length; x += len, y++) {
    $images.slice(x, x + len).wrapAll('<div class="container' + y + '" />');
}

, .image, .

, x y .

, div "container y".

+1

Source: https://habr.com/ru/post/1772934/


All Articles