Search code examples
jquerydomclone

How to clone cloned DOM objects in jQuery


I have <div class="OptionRow">s followed by a <a class="AddGroup">

Inside the .OptionRows, I have an X to remove that row.

The .AddGroup works fine until I X the original element that was cloned. Here's my code for the cloning and the X

$('.AddGroup').click(function(e) {
    e.preventDefault();
    var $this = $(this);
    $this.parent().siblings('.OptionRow:first').clone(true, true).hide().insertBefore($this).fadeIn();
});
$('.CloseGroup').click(function(e) {
    e.preventDefault();
    $(this).parents('.OptionRow').fadeOut('fast', function() {
        $(this).remove();
    });
});

Solution

  • As per @Microprocessor's suggestion, I examined the HTML and realized the .OptionRow clone was being inserted into the wrong place in the DOM. I solved the problem by using .insertBefore($this.parent()) instead of .insertBefore($this). Thanks @Microprocessor, I don't know why I didn't do that earlier.