Jquery - group or concatenate jquery objects created by a loop, so use appendTo only once

I have a loop forto generate string divs, my code

for(j=0; j<7; j++) {
   $('<div/>', {
     id: 'unique',
     html: 'whatever'
}).appendTo('#container');

This code seems to be looking for #container for each iteration and adding a new div to it.

How to write code so that I can first create all the divs and then add everything to the container all at once? Sorry, I tried to find keywords like concatenate / group / add jquery objects and it doesn't seem to have the correct search results.

TIA

+5
source share
2 answers

Xander solution should work fine. I personally don't like working with "long" HTML lines in js. Here is a solution that looks more like your code.

var elements = [];
for(j=0; j<7; j++) {
    var currentElement = $('<div>', { id: i, text: 'div' });
    elements.push(currentElement[0]);
}
$('#container').append(elements);
+7

var htm = '';
for(j=0; j<7; j++) {
     htm+= '<div id="unique_'+i+'">whatever</div>';
}

$('#container').html(htm); // Or append instead of html 
+4

All Articles