Create Duplicate of the elements with .clone() – jQuery

The .clone() method creates a duplicate of the matched elements. It allows either event handler will be copy or not, it by default doesn’t copy attached events.

This simplifies your code when you need to make a clone of the group of elements. You don’t have the need to create each group element and insert it.

In this tutorial, I show how you can use the jQuery .clone() method to create the clone of the elements.

Create Duplicate of the elements with .clone() – jQuery


Contents

  1. .clone()
  2. Example
  3. Event handler
  4. Generate unique id
  5. Conclusion

1. clone()

You only need to include the jQuery library for using this method.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
  • Creat clone

Call the .clone() method on the selector which you want to copy and insert the newly created element in your existing HTML layout using append, pretend, insertAfter, etc.

Syntax – 

$( selector ).clone();

Example

$( ".txt").clone();
  • Copy event handler

Pass true in the .clone() method to copy the event handler. It defaults set to false.

Syntax –

$( selector ).clone( true );

Example

$( ".txt").clone(true);

2. Example

On Add new button click create the duplicate of <div class='input-form'>.

HTML

Created a <div class='input-form'> which have two input element and a button to create copy of <div class='input-form'> using jQuery.

<div class='input-form'>
   <input type='text' placeholder='Enter name' id='name_1' class='txt' >
   <input type='text' placeholder='Enter email' id='email_1' class='txt' >
</div>
<input type='button' id='but_add' value='Add new'>

jQuery

I create the clone of last <div class='input-form'> and add after last class element.

NOTE – I don’t copied events here, the focus and focusout event handler doesn’t trigger on the newly elements.

$(document).ready(function(){

    $('#but_add').click(function(){

         // Create clone of <div class='input-form'>
         var newel = $('.input-form:last').clone();

         // Add after last <div class='input-form'>
         $(newel).insertAfter(".input-form:last");
    });

    $('.txt').focus(function(){
         $(this).css('border-color','red');
    });
 
    $('.txt').focusout(function(){
         $(this).css('border-color','initial');
    });

});

View Demo


3. Event handler

It copies the event handler as well while creating the clone. For this pass true in the clone() method.

By default, it set to false.

Completed Code

$(document).ready(function(){
 
    $('#but_add').click(function(){
 
         // Create clone of <div class='input-form'>
         var newel = $('.input-form:last').clone(true);
 
         // Add after last <div class='input-form'>
         $(newel).insertAfter(".input-form:last");
    });

    $('.txt').focus(function(){
         $(this).css('border-color','red');
    });
 
    $('.txt').focusout(function(){
         $(this).css('border-color','initial');
    });
});

View Demo


4. Generate unique id

The .clone() method completely copied the element. The newly created element has the same id as of the selector element.

You will face a problem when you try to retrieve the value by id better way to avoid this use the class instead if you want.

You can modify the id attribute after creating the element using .attr().

Completed Code

$(document).ready(function(){
 
   $('#but_add').click(function(){

       // Selecting last id 
       var lastname_id = $('.input-form input[type=text]:nth-child(1)').last().attr('id');
       var split_id = lastname_id.split('_');

       // New index
       var index = Number(split_id[1]) + 1;

       // Create clone
       var newel = $('.input-form:last').clone(true);

       // Set id of new element
       $(newel).find('input[type=text]:nth-child(1)').attr("id","name_"+index);
       $(newel).find('input[type=text]:nth-child(2)').attr("id","email_"+index);

       // Set value
       $(newel).find('input[type=text]:nth-child(1)').val("name_"+index);
       $(newel).find('input[type=text]:nth-child(2)').val("email_"+index);
  
       // Insert element
       $(newel).insertAfter(".input-form:last");
   });

});

View Demo


5. Conclusion

This method is helpful to create the exact copy of the matched elements.

If you are using element ids to manipulate data then you need to change the id after creating the element.

If you found this tutorial helpful then don't forget to share.