jQuery Minute™

…a jQuery Minute™ later and you're done!

Duplicate and Clone Elements Multiple Times

without comments

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:


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.

<ul id="myList">
    <li><a href="http://www.flickr.com/photos/jdsharp-com/4088227698/">Percheron's are cool</a></li> 

So here’s an example use case given the HTML above:


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:

$.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

Written by jdsharp

November 9th, 2009 at 8:15 am

Leave a Reply