Quick Tip: Use jQuery to Clone Objects

There’s a really handy .clone() method in jQuery that allows you to copy an HTML element dynamically using a script. This method comes in handy when you want to clone an element after a certain trigger event, like .click() or .hover(). Using the .clone() method is pretty straightforward. Here’s what you would need to do to clone a div with the class .thediv:

var clone = $('div').clone();

The above code will easily clone any HTML element, but if you want to clone a JavaScript object, you’ll need to use different code like in the example below:

var clonedObject = jQuery.extend({}, originalObject);

To use this code to, for example, clone a div after it’s been clicked and then insert the cloned div below the original div, you can use the following code snippet as a guideline:

Continue Reading Below
$("div").click(function () {
 $(this).clone().insertAfter(this);
});

Play around with the .clone() method to see what you can accomplish with it and discover all the different ways you can use it in your projects.


Comments are closed.

Sorry, but comments for this entry are now closed.