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!
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.
for loop includes three parts: initialization, condition and iteration.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With