Duplicate and Clone Elements Multiple Times
Greeting again from the heartland. Here is a quick plugin that duplicates one or more elements n times. This function is similar to the clone() method but will clone the elements multiple times placing them in the same collection. If you were to call clone 5 times such as:
1 | $('<div></div>').clone().clone().clone().clone().clone(); |
it would give you 5 separate collections of a div. The duplicate plugin below, puts a new collection of all elements duplicated on the jQuery stack.
1 2 3 | <ul id="myList">
<li><a href="http://www.flickr.com/photos/jdsharp-com/4088227698/">Percheron's are cool</a></li>
</ul> |
So here’s an example use case given the HTML above:
1 | $('li').duplicate(5).appendTo('#myList'); |
The above code starts by selecting all LI on the page (in this case only 1 of them) then duplicate’s it 5 times and appends the duplicated element to the UL with an ID of myList.
Now for the plugin:
1 2 3 4 5 6 7 | $.fn.duplicate = function(count, cloneEvents) { var tmp = []; for ( var i = 0; i < count; i++ ) { $.merge( tmp, this.clone( cloneEvents ).get() ); } return this.pushStack( tmp ); }; |
Having this plugin return this.pushStack( tmp ) is what gives us a new collection. To pop this collection off the stack and return to our original elements call .end(). One final note, cloneEvents can be set to true to have jQuery’s clone method also clone any attached events. By default it clones just the element and not attached events.
That’s all for now!
- Jonathan
Okay, I’ll bite. Where does cloneEvents come from here?
Steven Black
9 Nov 09 at 11:06 am
Thanks for your comment (even though you found the answer after posting it)! I’ve updated the article to explain the cloneEvents argument for copying events to the new elements during the clone process.
Cheers,
- Jonathan
jdsharp
13 Nov 09 at 3:26 pm