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?
Insert Multiple Elements with append() & prepend() MethodThe jQuery append() and prepend() also supports passing in multiple arguments as input. The jQuery code in the following example will insert a <h1> , <p> and an <img> element inside the <body> element as a last three child nodes.
To append multiple child elements with JavaScript, we can use the append method. Then we write: const listElement = document. querySelector('ul') const listItem = document.
prepend() method inserts a set of Node objects or string objects before the first child of the Element . String objects are inserted as equivalent Text nodes.
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.
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