Skip to content

Instantly share code, notes, and snippets.

@seutje
Created June 20, 2011 14:47
Show Gist options
  • Save seutje/1035745 to your computer and use it in GitHub Desktop.
Save seutje/1035745 to your computer and use it in GitHub Desktop.
jQuery plugin to wrap every x items with element y
// Expose the Array.reverse() method on jQuery objects
$.fn.reverse = [].reverse;
/**
* takes a jQuery collection and wraps each x items with element y
* kinda nasty looking though
* example: $('.foo').children().wrapInChunks('<div class="bar" />', 3);
* wraps every 3 children of .foo in div.bar
* NOTE: Needs a way to distinguish the wrapper from the wrapped elements,
* ergo, wrapping classless, IDless DIVs with classless, IDless DIVs will error out
*/
jQuery.fn.wrapInChunks = function(html, chunkSize) {
chunkSize = chunkSize || 1;
var items = this.get(),
collection = this,
rows = [],
cur = rows[0] = html,
amount = this.length,
helper = function(times, $el) {
var $that = $el,
$html = $(html),
classes = $html.attr('class'),
myId = $html.attr('id'),
checker = $html[0].nodeName,
classes2,
myId2,
checker2;
checker += classes.length ? '.' + classes.split(' ').join('.') : '';
checker += myId && myId.length ? '#' + myId : '';
while (times--) {
$that = $that.prev();
classes2 = $that.attr('class');
myId2 = $that.attr('id');
checker2 = $that[0].nodeName;
checker2 += classes2.length ? '.' + classes2.split(' ').join('.') : '';
checker2 += myId2 && myId2.length ? '#' + myId2 : '';
if (!$that.is(checker) && collection.filter(checker2).length) {
$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.reverse().wrapAll(html);
}
else {
if (i == amount) {
var num = i % chunkSize -1,
$that = $this;
$this = helper(num, $that);
$this.reverse().wrapAll(html);
}
}
});
};
@seutje
Copy link
Author

seutje commented Jul 6, 2011

seriously need a better way to check if we are still dealing with elements in the original collection
ergo, get rid of (!$that.is(checker) && collection.filter(checker2).length) and everything that's got to do with it

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