views:

11

answers:

1

Does anyone know a good way to cache a collection of objects returned by a selector.

var $platforms = $(".platforms");    
var i = 0, l = $platforms.length, current;

for(;i<l;i++) {
    current = $($platforms[i]); //calling jQuery() in a loop. Should be cached
}

The above code creates a jQuery instance of each element returned by $(".platform") when it should be cached. Is there any easy way to do this?

+2  A: 

To literally get an array of jQuery wrappers of elements, you can use .map() like this:

var $platforms = $(".platforms").map(function() { return $(this); }).get();

Then in your for loop $platforms[i] will be a jQuery object.


It depends what you're after though, there's .each() like this:

$(".platforms").each(function(i,elem) {
  var current = $(this);
});

Or use .eq() to get a jQuery wrapped element at that index in your loop, like this:

for(;i<l;i++) {
  current = $platforms.eq(1);
}

It all depends on what you're after....why are you looping through the elements? Most jQuery operations operate on sets, not individual elements, so for example $(".platforms").bind(...) would bind to all of the elements that selector found.

Nick Craver
Very good point. Although `$(this)` is still calling the jQuery function and in my case (a game) that means a lot of function calls that isn't necessary. Need to find the `position()` for each. My current solution is to check it at onload, then cache the values in an array but was wondering if a nice solution existed.
Louis
@Louis - you could maintain an array of the jQuery wrapped version of the elements if you're repeatedly looping like this, for example: `var $platforms = $(".platforms").map(function() { return $(this); }).get();` then you can do `$platforms[i]` and it'll be a jQuery wrapper.
Nick Craver
Nice, I like that! Could you add it to the answer so I can accept.
Louis
@louis - done :)
Nick Craver