A simpler way to restrict entries in a .each () loop

I wanted to know if there is a good jQuery-esque way to do the following:

var count = 0; $("p").each(function() { if (count >= 5) return false; $(this).toggleClass("highlight"); count++; }); 

Is there a similar function in jQuery like each() that will allow me to set a limit on the number of elements that it will iterate over, or is this the best way to do something?

+7
source share
6 answers

The simplest .slice thing:

 $("p").slice(0, 5).toggleClass("highlight"); // only <p>s from index 0 (inclusive) to 5 (exclusive) 
+13
source

You can simply limit the selected items: $("p:lt(5)").toggleClass("highlight");

+4
source

Take a look at slice() . This will split the array returned by $("p") for use with .each() :

 $("p").slice(0, 4).each(function() { // Do stuff }); 

.slice() takes a start and end index as parameters. In the above example, we start from the first element of the array (index 0) and return the next 5 elements to index 4.

+3
source

Will it work for you?

 $("p").each(function(index){ if (index >4) { return false; } ... }); 
+2
source

Another way to write this with filter :

 $("p").filter(function(index) { return index < 5 }).toggleClass("highlight"); 
+1
source

Use the for loop to repeat the loop a certain (known in advance) number of times. If the number of repetitions is unknown, use a while loop (or each is an analog of functional programming)

So,

 var i; for (i = 0; i < 6; i += 1) { $("p")[i].toggleClass("highlight"); } 
0
source

All Articles