Skip to content

Instantly share code, notes, and snippets.

@lutzissler
Last active October 12, 2015 18:58
Show Gist options
  • Save lutzissler/4072102 to your computer and use it in GitHub Desktop.
Save lutzissler/4072102 to your computer and use it in GitHub Desktop.
Wrap groups of matched elements (jQuery)
(function ($) {
// From http://forloop.co.uk/blog/wrap-child-elements-in-groups-in-jquery
// Modified to work much simpler
$.fn.wrapGroups = function(options) {
options = $.extend({
groupSize : false,
groupCount: false,
wrapper : '<div>'
}, options || {});
var elems = $(this),
len = pos = 0;
if (!options.groupSize) {
options.groupSize = options.groupCount ? Math.ceil(elems.length/options.groupCount) : 1;
}
return elems.each(function(i,value) {
len = len + 1;
if (len > 0 && (len % options.groupSize === 0) || (i === elems.length - 1)) {
elems.slice(pos,i + 1).wrapAll(options.wrapper);
len = 0;
pos = i + 1;
}
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment