Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a for loop to generate a row of divs, 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

like image 405
Jamex Avatar asked Mar 10 '12 02:03

Jamex


People also ask

Why is only one argument being supplied to jQuery extend ()?

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.

How to use each() method in jQuery?

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:

How do I merge two arrays together in jQuery?

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.

How do I iterate over a non-jQuery object?

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.


2 Answers

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);
like image 114
j-u-s-t-i-n Avatar answered Sep 28 '22 07:09

j-u-s-t-i-n


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 
like image 39
Jose Adrian Avatar answered Sep 28 '22 07:09

Jose Adrian