Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I add multiple identical elements to a div with jQuery

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?

like image 503
Ken Avatar asked Oct 14 '08 15:10

Ken


People also ask

Can you append multiple items jQuery?

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.

Can you append multiple elements in JavaScript?

To append multiple child elements with JavaScript, we can use the append method. Then we write: const listElement = document. querySelector('ul') const listItem = document.

What does prepend() do?

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.


1 Answers

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.

like image 100
Remy Sharp Avatar answered Sep 23 '22 22:09

Remy Sharp