Reputation: 91770
I've been wanting to know if there's 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 as each()
in jQuery that will allow me to set a limit on how many items it'll loop over, or is this the best way of doing things?
Upvotes: 8
Views: 10519
Reputation: 97641
Another way to write it is using filter
:
$("p").filter(function(index) { return index < 5 }).toggleClass("highlight");
Upvotes: 1
Reputation: 2890
Use a for loop to repeat the loop a certain (known in advance) number of times. If the number of repetitions is not known, use a while loop (or each - an analogue from the functional programming)
So,
var i;
for (i = 0; i < 6; i += 1) {
$("p")[i].toggleClass("highlight");
}
Upvotes: 0
Reputation: 37382
Will it work for you?
$("p").each(function(index){
if (index >4)
{
return false;
}
...
});
Upvotes: 2
Reputation: 318598
You can simply limit the elements selected: $("p:lt(5)").toggleClass("highlight");
Upvotes: 5
Reputation: 101533
Have 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 array element (index 0) and return the next 5 elements up to index 4.
Upvotes: 5
Reputation: 154918
Simplest thing is .slice
:
$("p").slice(0, 5).toggleClass("highlight");
// only <p>s from index 0 (inclusive) to 5 (exclusive)
Upvotes: 14