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!

4
  • 1
    Are you simply looking for i%3 ? Commented Jun 18, 2013 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. Commented Jun 18, 2013 at 16:21
  • @dystroy - Yes, exactly what I was looking for. Is there some documentation you can link to? Thanks! Commented Jun 18, 2013 at 16:27
  • @MikelWard There's this one. Commented Jun 18, 2013 at 16:30

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.