JQuery

Is it possible to run the jQuery.each statement a certain number of times, and not for each of the repeating elements? The repeated JSON is the last.fm feed, and of course they often ignore the "limit" request. I would like to get around this error by simply following the .each statement so many times.

+7
jquery each
source share
5 answers
var limit = 5; $("somelement").each(function(i, val) { if(i > limit) return false; // do stuff }); 

or

 $("somelement:lt(5)").each(function() { // do stuff }); 
+19
source share

Instead of modifying .each, change your selector to select only the first "n" elements.

http://docs.jquery.com/Selectors/lt#index

+11
source share

The best solution is to use a method . slice in jQuery.

 var limit = 5; $("somelement").slice(0, limit).each(function(i, val) { // do stuff }); 
+4
source share

Define a variable before your loop, increase it within each and if(myvar == 10){return false;}

Returning "false" from each function completely stops the loop http://docs.jquery.com/Core/each

+2
source share

Return false from the iterator when you want to stop. The first parameter of your iterator is the index (when navigating through arrays).

+1
source share

All Articles