13

I am trying to get a <div class="clear"></div> to appear after every third iteration of a for loop in jquery. I know in PHP it can be accomplished via if($i%3 == 0) but how does one do it in jquery/javascript?

Here is my for loop:

var data = $.parseJSON(result);
for(i=0;i<data.length;i++){
    if(i/3 == 1){
        $('#add_product_preview_area').append('<div class="clear"></div>');
    }
    $('#add_product_preview_area').append(data[i]);
}

Now this only works once since the loop will only get to the number 3 once. So any thoughts on how to make the same php concept work in jquery? I have seen the other questions about wrapping every nth in a div, but I just need to write the html of a div after each one.

Thanks in advance.

EDIT:

if ( i && (i % 3 === 0)) {

Is the answer..I didn't know you could do that. Thanks!

3
  • Why can't you use the same logic here? Commented Oct 30, 2012 at 17:57
  • Did you try what you did in PHP with JavaScript? You might be surprised. Commented Oct 30, 2012 at 17:57
  • 1
    The '%' modulus operator still exists: stackoverflow.com/questions/2821006/… Commented Oct 30, 2012 at 17:58

2 Answers 2

23

Use the modulus operator instead.

if ( i && (i % 3 === 0)) { ...

Whenever there's no remainder, you're evenly divisible by 3.

I included the i && to eliminate the first iteration since 0 % 3 === 0; // true.

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

1 Comment

I swear i had already tried the php method and it didn't work..woops. thanks!
4

Use this... just like your PHP

if (i % 3 == 0 ) 

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.