JQuery adds an item more than once

I am currently trying to add n the number of divs at the bottom of the body, but using this code:

star = $('<div class="star" />'); for(i=0; i<12; i++) { $('body').append(star); } 

results in adding only one div to the lower body. I guess this is because the contents of the body are not updated between each iteration of the for loop, but cannot figure out how best to solve it.

+7
source share
5 answers

Instead of doing 12 modifications to the DOM, why not multiply the string and then use only one .append() call?

 String.prototype.times = function(n) { return Array.prototype.join.call({length: n+1}, this); }; var star = '<div class="star" />'.times(12); $('body').append(star); 

jsFiddle


Fix source method

If you want to stay with your method, you need to call the $ function inside the loop so that a separate jQuery object is created at each iteration. I guess this is slower, but it will work.

 star = '<div class="star" />'; var body = $('body'); for ( i = 0; i < 12; i++ ) { body.append($(star)); } 

jsFiddle

+15
source

try it

 var star = '<div class="star" />SomeTest</div>'; for(i=0; i<12; i++) { $('body').append(star); } 
+2
source
 $('body').append(new Array(13).join('<div class="star" />')); 
+2
source

It should be noted that using the FOR loop is worse than iterating with the jquery.each () function, because the FOR loop is not asynchronous and therefore much slower on a larger scale, since each () instance runs side by side when the FOR loop waits for each iteration to complete before continuing with the next iteration.

(I can’t just comment because of the requirement of 50 rep.)

0
source

 $(document).ready(function() { star = '<div class="star" />'; var body = $('body'); for ( i = 0; i < 12; i++ ) { body.append($(star)); } }); 
 .star { border: 1px solid black; height: 20px; width: 100px;margin-bottom:1px } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
0
source

All Articles