Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simpler way to limit entries in a .each() loop

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?

like image 886
Naftuli Kay Avatar asked Nov 20 '11 19:11

Naftuli Kay


2 Answers

Simplest thing is .slice:

$("p").slice(0, 5).toggleClass("highlight");
// only <p>s from index 0 (inclusive) to 5 (exclusive)
like image 138
pimvdb Avatar answered Sep 19 '22 00:09

pimvdb


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

like image 34
ThiefMaster Avatar answered Sep 20 '22 00:09

ThiefMaster