5

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

2
  • Why do you want to have the code only call appendTo once? Commented Mar 10, 2012 at 3:06
  • 1
    @JaredPar, because as I understand it, jquery only has to seek out the correct div once instead of many times as the iteration of the loop. Commented Mar 10, 2012 at 4:17

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks Justin, this is kinda what I had in mind. I do wonder if there is another way of 'grouping' objects, since this method introduces an array that could tax resources.
Yes, you could potentially pay a slight tax on the creation of jQuery objects. However, you get added benefits of more easily binding events (you'd probably want to delegate the events if they're the same for every element), plus this way gives you the added benefit of creating a closure on those events(not demonstrated here), if needed. I don't think you will see any performance gains until you reach thousands of elements.
Hi Justin, the code works, but I don't understand the line elements.push(currentElement[0]); Why does currentElement has the [0]?
It is because a jQuery object is created and you don't want to add the whole object just the first element in it. A jQuery object is similar to an array.
Thanks Justin, can you point me to where I can learn more about what elements are part of the object?
|
4

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 

2 Comments

Thanks Jose/Xander, I did not really want to do it that way because I didn't want to mess with writing the text string. I think Justin's code is more of what I had in mind.
OTOH, the creation of the string variable should be less taxing than jquery objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.