I have a for
loop to generate a row of div
s, my code is
for(j=0; j<7; j++) {
$('<div/>', {
id: 'unique',
html: 'whatever'
}).appendTo('#container');
This code seems to seek out #container for every iteration and appends a new div to it.
How do write the code so that I can go create all the divs first and then append to the container all at once? Sorry, I tried searching for keywords such as concatenate/group/add jquery objects, and don't seem to have the right search results.
TIA
If only one argument is supplied to $.extend (), this means the target argument was omitted. In this case, the jQuery object itself is assumed to be the target. By doing this, you can add new functions to the jQuery namespace.
The each () method in jQuery works similarly to JavaScript’s for loop. The each () method can iterate through arrays and objects. While, to iterate through objects in JavaScript, we need to use the for in Loop. Let’s see an example for the for loop from JavaScript:
jQuery.merge( first, second )Returns: Array. Description: Merge the contents of two arrays together into the first array. The first array-like object to merge, the elements of second added. The second array-like object to merge into the first, unaltered. The $.merge() operation forms an array that contains all elements from the two arrays.
Iterating over jQuery and non-jQuery Objects. jQuery provides an object iterator utility called $.each() as well as a jQuery collection iterator: .each(). These are not interchangeable. In addition, there are a couple of helpful methods called $.map() and .map() that can shortcut one of our common iteration use cases.
Xander's solution should work just fine. I personally don't like working with 'long' HTML strings in js. Here is a solution that looks more similar to your code.
var elements = [];
for(j=0; j<7; j++) {
var currentElement = $('<div>', { id: i, text: 'div' });
elements.push(currentElement[0]);
}
$('#container').append(elements);
This could help
var htm = '';
for(j=0; j<7; j++) {
htm+= '<div id="unique_'+i+'">whatever</div>';
}
$('#container').html(htm); // Or append instead of html
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