I wrote a plugin like so to grab a subset of a collection:
jQuery.range = function(start, end, includingTheLast) {
var ret = $([]), i = 0;
while (!this.eq(i).is(start) && i < this.length)
i++;
for (; i < this.length && !this.eq(i).is(end); i++) {
ret = ret.add(this[i]); // we can do better than this
}
if (includingTheLast) ret = ret.add(this[i]); // we can do better than this
return this.pushStack(ret, 'range');
}
It’s used like this:
$('a').range(':eq(2)', '#stop')...
Looking at ret = ret.add(this[i]) seems to be very slow, is this a smart way to do it? Should I build an array then turn it into a jQuery object? Is this micro-optimizing?
The jQuery constructor also accepts an array of DOM elements and wraps them in a jQuery object. So, if you are opposed to using .add, you could push them all to an array (as dom elements) and then wrap the whole thing at once.
I have not run a perf test to see what would be faster.
reference: http://api.jquery.com/jQuery/