1

How do I increment up to a specific number (3), then have it reset, looping back to the first number. The first number should begin at 1 (not 0).

I've tried using: i=1; i<=3; i+=1

Here's my basic code:

$(document).ready(function() {
    $(".std-price .local-pricing").each(function(i) {
            $(this).addClass("ab-price" + (i));
    });
});

If I used for() or each(), it would then give me class="ab-price1 ab-price2 ab-price3"

Any help and reference links (to learn in the process) would be great.

Thanks!

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Mikel
  • 117
  • 11
  • 1
    Are you simply looking for i%3 ? – Denys Séguret Jun 18 '13 at 16:11
  • if you need the # to be dynamic, you could also substitute 3 with `$(".std-price .local-pricing").length||0`. Or instead of a mod, just use `if (i==0) { i = 1 }` at the top of your function. – ginman Jun 18 '13 at 16:21
  • @dystroy - Yes, exactly what I was looking for. Is there some documentation you can link to? Thanks! – Mikel Jun 18 '13 at 16:27
  • @MikelWard There's [this one](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators). – Denys Séguret Jun 18 '13 at 16:30

2 Answers2

3

If you want to set the classes ab-price1, ab-price2, ab-price3, ab-price1, ab-price2, etc. then you can do this :

$(".std-price .local-pricing").each(function(i) {
    $(this).addClass("ab-price" + (1+(i%3)));
});

This uses the modulo operator.

If you don't need to be compatible with IE8, this could also be solved in pure CSS using the :nth-of-type() pseudo class.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

You can use the modulo operator:

$(".std-price .local-pricing").addClass(function(i) {
    return "ab-price" + (i % 3 + 1);
});

Also, quite a few jQuery functions take callbacks (e.g. addClass, width, attr, and prop), so you can usually get rid of each.

Blender
  • 289,723
  • 53
  • 439
  • 496