Skip to content

Instantly share code, notes, and snippets.

@iMoses
Created July 26, 2012 12:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save iMoses/3181731 to your computer and use it in GitHub Desktop.
Save iMoses/3181731 to your computer and use it in GitHub Desktop.
jQuery Plugin wrapInGroups
/**
* Takes a jQuery collection and wraps each 'groupSize' items with 'wrapHtml'
* Example: $('#Example span').wrapInGroups('<div/>', 4);
* Will wrap every 4 span's inside #Example with a div
* See for yourself: http://jsfiddle.net/M9ZFh/
* Author: iMoses (imoses.g@gmail.com)
*/
(function($) {
$.fn.wrapInGroups = function(wrapHtml, groupSize) {
var selector = this.selector;
groupSize = groupSize || 1;
this.filter(':nth-child(' + groupSize + 'n+1)').each(function() {
$(this).nextAll(selector + ':lt(' + (groupSize - 1) + ')').andSelf().wrapAll(wrapHtml);
});
};
})(jQuery);
@hmaesta
Copy link

hmaesta commented Apr 16, 2014

Nice work. Thank you.

@onemanparsons
Copy link

Found this very helpful, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment