Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery for loop write html after every third iteration of loop

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!

like image 474
klye_g Avatar asked Oct 30 '12 17:10

klye_g


People also ask

Can you write a for loop in HTML?

Approach 1: Using the for loop: The HTML elements can be iterated by using the regular JavaScript for loop. The number of elements to be iterated can be found using the length property. The for loop has three parts, initialization, condition expression, and increment/decrement expression.

What are the 3 parts of a for loop in JavaScript?

for loop includes three parts: initialization, condition and iteration.

Does for loop check condition every time?

Syntax. The for loop consists of three optional expressions, followed by a code block: initialization - This expression runs before the execution of the first loop, and is usually used to create a counter. condition - This expression is checked each time before the loop runs.

How do you repeat a loop in JavaScript?

you can use second for loop. in the second loop write how many times do you want to repeat first loop. Also you can use while loop.


1 Answers

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.

like image 173
I Hate Lazy Avatar answered Oct 23 '22 10:10

I Hate Lazy