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!

klye_g
  • 1,242
  • 6
  • 31
  • 54

2 Answers2

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.

I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
4

Use this... just like your PHP

if (i % 3 == 0 ) 
Justin Self
  • 6,137
  • 3
  • 33
  • 48