Skip to content

Instantly share code, notes, and snippets.

@seutje
Created April 18, 2011 16:00
Show Gist options
  • Save seutje/925602 to your computer and use it in GitHub Desktop.
Save seutje/925602 to your computer and use it in GitHub Desktop.
Takes a jQuery collection and wraps each x items with element y
/**
* takes a jQuery collection and wraps each x items with element y
* kinda nasty looking though
* Example: $('#foo').children().wrapInChunks('<div></div>', 2);
* would wrap every 2 children of #foo with a div
*/
jQuery.fn.wrapInChunks = function(html, chunkSize) {
chunkSize = chunkSize || 1;
var items = this.get(),
rows = [],
cur = rows[0] = html,
amount = this.length,
helper = function(times, $el) {
var $that = $el;
while (times--) {
$that = $that.prev();
$el = $el.add($that[0]);
}
return $el;
};
return this.each(function(i, el) {
var $this = $(this);
i++;
if (i % chunkSize == 0) {
var num = chunkSize,
$that = $this;
$this = helper(num, $that);
$this.wrapAll(html);
}
else {
if (i == amount) {
var num = i % chunkSize -1,
$that = $this;
$this = helper(num, $that);
$this.wrapAll(html);
}
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment