Skip to content

Instantly share code, notes, and snippets.

@Striker21
Forked from padolsey/gist:500145
Created November 9, 2011 20:57
Show Gist options
  • Save Striker21/1352993 to your computer and use it in GitHub Desktop.
Save Striker21/1352993 to your computer and use it in GitHub Desktop.
quickEach
// $.quickEach() replicates the functionality of $.each() but allows 'this'
// to be used as a jQuery object without the need to wrap it using '$(this)'.
// The performance boost comes from internally recycling a single jQuery
// object instead of wrapping each iteration in a brand new one.
// Development -----------------------------------
(function($)
{
$.fn.quickEach = function(f)
{
var j = $([0]), i = -1, l = this.length, c;
while(
++i < l
&& (c = j[0] = this[i])
&& f.call(j, i, c) !== false
);
return this;
};
})(jQuery);
// Minified --------------------------------------
(function($){$.fn.quickEach=function(f){var j=$([0]),i=-1,l=this.length,c;while(++i<l&&(c=j[0]=this[i])&&f.call(j,i,c)!==false);return this}})(jQuery);
// Usage -----------------------------------------
(function($)
{
$('div').quickEach(function(i, el)
{
//'this' is a jQuery object
//'i' is the index
//'el' is the DOM element
//Print the index of each element
this.html('Index: '+i);
});
})(jQuery);
@Striker21
Copy link
Author

You are correct. If you plan on referencing one of the objects again you will need to wrap it if you plan on using jQuery functions on it. In that scenario, you may be better off using standard $.each().
However, if you're storing a reference to the entire collection, then quickEach is still the better option. This is what you'd do:

var myCollection = $('div'); //You now have a variable referencing all of the divs

myCollection.quickEach(function(i, e)
{
    /* Do stuff */
});

//Later on, do stuff to the same collection
myCollection.quickEach(function(i, e)
{
    /* Do more stuff */
});

/* Do even more stuff */
myCollection.addClass('foo');

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