Jquery Duplicate DIV into Another DIV
This jQuery
line of code clones a DIV with class .source
and then appends it to a DIV with class .target
. The contents are duplicated, resulting in a sheepie clone of your element.
Since we're manipulating DOM elements, always ensure to wrap your code within $(function() { /* insert jQuery magic here */ });
. This waits for the DOM to load completely before executing your scripts.
The nitty gritty of .clone()
A brief on .clone()
Using jQuery's .clone()
function, creates a deep copy of the set of matched elements. This includes all child nodes, text, and attributes (such as classes and IDs). To only clone the elements not the data or events attached to it, use .clone(false)
. Sounds easy, like CTRL+C and CTRL+V huh!
Cloning and selectors
Be sure that your jQuery selectors are precise enough to directly target the desired DIVs. If the .source
class is used elsewhere, consider adding a parent selector or an extra class to pinpoint the exact DIV.
Appending and other methods
The .appendTo()
function puts the jQuery object at the end of the target
DIV. But if you want more control with the position of the cloned DIV, jQuery provides other handy functions such as .prependTo()
, .insertBefore()
, and .insertAfter()
.
Deeper into cloning and more
Exclude specific elements
You could also desire to clone a DIV
but exclude certain elements. In this case, use the .not()
function:
The result - the cloned DIV
will not carry over any elements with the class .exclude
.
Cloning multiple DIV elements
Looping through and cloning multiple elements is simple with a .each()
loop chained to .clone()
:
Mindful cloning of form elements
When working with form elements, the unique identifiers and values should be preserved. Clearing the input field values can be done with .val('')
chained to the cloned inputs:
Many forms, no data confusion!
Beware of booby traps!
Event handlers
Reattaching event handlers after cloning becomes vital if the original elements had interactions associated with them that should also apply to the clones. This can be achieved by rebinding the events:
Efficient scripting
Cloning large structures can negatively impact performance. Always optimize your selectors and try to minimize the calls to .clone()
, it's kind of like cutting down on unhealthy fast food ๐.
'Sir Unique-a-lot'
Maintaining unique IDs after cloning is crucial for the validity of your page elements. If working with elements having IDs, make sure the cloned elements are assigned new unique IDs.
Was this article helpful?