Take a look at this jsfiddle
But for a detailed explanation:
Some announcements:
var $records = $('.record'), // get all records total = 0, // current height of all elements group = 0, // iterator for groups limit = 200; // your limit in px for each .page (put your 1000 here)
First cycle:
$records.each(function() { var $record = $(this); total += $record.outerHeight(true); // sum height of all records // when total height overflow your limit // reset total and set next group index if (total > limit) { total = $record.outerHeight(true); group++; } // assign group index to each record $record.attr('data-group', group); });
And the second cycle:
// iterate on all groups and using jQuery .wrappAll() // wrap all records from one group to .page element for (var i = 0; i <= group; i++) { $('[data-group="' + i + '"]').wrapAll('<div class="page"></div>') }
Learn more about jQuery.wrappAll ()
Take a look at .outerHeight(true) and all CSS margins/paddings/borders , etc., because in this solution they will be taken into account in the example (I don't know if this is normal for you)
source share