0

I am using jquery 1.10.2 and trying to clone a div, which I have done successfully, but I also need to change the id's of that div and all of its children, which I am currently unsuccessful at.

I have search this and found several examples to help e.g this and this, but they havent worked for. I really cant see why. I know I must be doing something really obvious wrong. What is the reason for what i have done not to work? (I have l left my attempts in - but commented)

$(document).ready(function () {
$("#btnSecondContact").click(function () {
    $("#divCustomerData").removeClass("col-lg-6 col-md-6");
    $("#divCustomerAddr").removeClass("col-lg-6 col-md-6");
    $("#divCustomerData").addClass("col-lg-4 col-md-4");
    $("#divCustomerAddr").addClass("col-lg-4 col-md-4");
    $('#divCustomerData').after(
        $('#divCustomerData').clone()
        //$('#divCustomerData').clone().attr("id", "newId").find("#divCustomerData").attr("id", "#divCustomerData_cloned")

        //$('#divCustomerData').clone(function () {
        //    $(this).attr("id", $(this).attr("id") + "_cloned")
        //})
    )
    //$("#divCustomerData").clone(false).find("*[id]").andSelf().each(function () { $(this).attr("id", $(this).attr("id") + "_cloned"); });
    $("#btnSecondContact").prop('disabled', true);
})

});

Community
  • 1
  • 1
tony09uk
  • 2,841
  • 9
  • 45
  • 71

1 Answers1

0

You're calling clone too many times and lose your reference.

Change this

$('#divCustomerData').after(
        $('#divCustomerData').clone()
        //$('#divCustomerData').clone().attr("id", "newId").find("#divCustomerData").attr("id", "#divCustomerData_cloned")

        //$('#divCustomerData').clone(function () {
        //    $(this).attr("id", $(this).attr("id") + "_cloned")
        //})
    )

To

var $clon = $('#divCustomerData').clone();
 $('#divCustomerData').after(
    $clon.attr("id", "newId").find("#divCustomerData").attr("id", "#divCustomerData_cloned")
)

Also notice that clone doesn't take a function :

So I don't know what you've tried to do in here :

//$('#divCustomerData').clone(function () {
        //    $(this).attr("id", $(this).attr("id") + "_cloned")
        //})
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • thanks for the quick response. But trying that does not work. however If I simply use $clon then I get the cloned elements, but obviously I still have the problem that ids are not changed – tony09uk Aug 09 '15 at 08:19