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:

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

Written by jdsharp

November 9th, 2009 at 8:15 am

Leave a Reply