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?
Simplest thing is .slice
:
$("p").slice(0, 5).toggleClass("highlight");
// only <p>s from index 0 (inclusive) to 5 (exclusive)
You can simply limit the elements selected: $("p:lt(5)").toggleClass("highlight");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With