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?
To literally get an array of jQuery wrappers of elements, you can use
.map()like this:Then in your
forloop$platforms[i]will be a jQuery object.It depends what you’re after though, there’s
.each()like this:Or use
.eq()to get a jQuery wrapped element at that index in your loop, like this: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.