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
divstr = '<div></div><div></div>...<div></div>';
and then injecting that into my container:
$('#container').html(divstr);
Is there a more elegant way to insert multiple, identical elements?
I’m hoping to find something that wouldn’t break chaining but wouldn’t bring the browser to its knees. A chainable .repeat() plugin?
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/
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.