I need to add multiple empty divs to a container element using jQuery.
At the moment I am generating a string containing the empty html using a loop
You can wrap a native JavaScript array in a jQuery and use map() to transform it into a jQuery (list of DOM nodes). This is officially supported.
$(['plop', 'onk', 'gloubi'])
.map(function(i, text)
{
return $('<div/>').text(text).get(0);
})
.appendTo('#container');
This will create
<div id="container">
<div>plop</div>
<div>onk</div>
<div>gloubi</div>
</div>
I often use this technique in order to avoid repeating myself (DRY).
You can use a regular loop with the Jquery append function.
for(i=0;i<10; i++){
$('#container').append("<div></div>");
}
If you want IE to be fast - or generally consider speed, then you'll want to build up a DOM fragment first before inserting it.
John Resig explains the technique and includes a performance benchmark:
http://ejohn.org/blog/dom-documentfragments/
var i = 10,
fragment = document.createDocumentFragment(),
div = document.createElement('div');
while (i--) {
fragment.appendChild(div.cloneNode(true));
}
$('#container').append(fragment);
I realise it's not making a lot of use of jQuery in building up the fragment, but I've run a few tests and I can't seem to do $(fragment).append() - but I've read John's jQuery 1.3 release is supposed to include changes based on the research linked above.
The fastest way to do this is to build the content first with strings. It is MUCH faster to work with strings to build your document fragment before working with the DOM or jquery at all. Unfortunately, IE does a really poor job of concatenating strings, so the best way to do it is to use an array.
var cont = []; //Initialize an array to build the content
for (var i = 0;i<10;i++) cont.push('<div>bunch of text</div>');
$('#container').html(cont.join(''));
I use this technique a ton in my code. You can build very large html fragments using this method and it is very efficient in all browsers.