JQuery clone() with new Ids

 JQuery clone() with new unique ids

In my previous post, I explained how to use JQuery clone() function to make copy of DOM elements. JQuery clone() method is a nice and quick way to create copy of elements. However, there is a drawback of using this function. It creates cloned elements with duplicate ids, which should be unique inside DOM.

To overcome this problem, you need to add your own code to replace duplicate ids with new unique ids because JQuery doesn’t provide this functionality so far. There are multiple ways to handle this problem.

  1. You can use RegExp and replace old Ids with new one before inserting cloned element into DOM.
  2. Iterate through the elements and replace values of id attribute with newly generated ids.

We can take up any approach but the objective here is the same i.e. “replacing old ids with new unique ids”. For this post, I would be using second approach to generate new unique ids. Let’s write some code and see how to achieve this using JQuery clone() method. Consider the below HTML

 

<div id="containerDiv" class="div_border">
    <input type="text" id="txtname" /><br />
    <select id="cmbcities">
         <option value="1" selected="selected">City 1</option>
         <option value="2">City 2</option>
         <option value="3">City 3</option>
         <option value="4">City 4</option>
         <option value="5">City 5</option>
    </select><br />
    <input type="checkbox" id="chkcitizen" />
</div>
<input type="button" id="btncloneme" value="Click me to clone."/>

Attach one event handler to the button which will call our new clone method “cloneWithNewIds” on click event of the button.

  $(document).ready(function () {
        $("# btncloneme ").click(function () {
            $("#containerDiv").cloneWithNewIds().insertAfter("#containerDiv");
        });
});

Finally, we need a custom function to create clone with new ids.

 

    ; (function ($) {
        $.fn.cloneWithNewIds = function () {
            var newsuffix = ($("[id*='" + $(this)[0].id + "']").length);
            var clonedelement = this.clone(true);
            $(clonedelement)[0].id = $(clonedelement)[0].id + "_" + newsuffix;
            $(clonedelement).find('*').each(function (index, element) { 
                if (element.id) {
                    element.id = element.id + "_" + newsuffix;
                }
            });
            return clonedelement;
        };
    })(jQuery)

 

In the above function, we first find out the count of elements containing same values for the id attribute as our original element i.e. the id of the element to be cloned.

Next, we clone the element with deep cloning options of JQuery and update its id by adding new Id as suffix.

Then, we simple traverse through all the elements inside the container element and update their ids (just like we did for main container element).

Finally, return the cloned element.

After cloning element using above function, cloned elements should look like below HTML

<div class="div_border" id="containerDiv_1">
    <input id="txtname_1" type="text" value=""><br>
    <select id="cmbcities_1">
         <option selected="selected" value="1">City 1</option>
         <option value="2">City 2</option>
         <option value="3">City 3</option>
         <option value="4">City 4</option>
         <option value="5">City 5</option>
    </select><br>
    <input id="chkcitizen_1" type="checkbox" value="on">
</div>

 

Above code is just a sample on how we can clone an element with new unique ids.  In this example we simply append “_<newID>” to the existing id to make it unique. But you can extend this sample into more complex logic to create new ids and values of other attributes like name etc which suites your requirement. You may like to use .uniqueId() method to generate unique ids which is introduced in JQuery 1.9 version.

You can also extend this piece of code and use it as a JQuery plugin.

 

I hope you have enjoyed this article. Please leave your comments/suggestion if you like this post.

 

 

 

 

One thought on “JQuery clone() with new Ids

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>