Is there a difference between a cloned div and a div created in a loop?

Is there a difference between a clone div and a div generated in a loop? I have two situations,
div 1:

$('.div1').clone(true).insertAfter('.created_form');

      

div 2:
loop

<div class="div2"></div>

      

ENDLOOP

I have a button in each div to remove the div when the button is clicked. But the delete button only works for the cloned div (div1).
For div 2 doesn't work.
My code to remove the div:

$('.buttons').on('click', '.minus_sign', function() {
        var parent_id = $(this).parent().attr('id');
        $("#"+parent_id).remove();
        $("input[name='"+parent_id+"']").remove();              
    });

      

Can someone tell me why this doesn't work for both please? I mention that div is the same, only the id is different! Thanks you

+3


source to share


2 answers


This is because the one that is created without a clone has no attribute id

.

<div class="div2"></div>

      

However, if you gave it an id:



<div id="myDiv" class="div2"></div>

      

it will work.

0


source


Assuming the original element has an attribute id

, the one you create inside the loop does not have an attribute id

as stated in this answer .

Even if it is, since you are using the .clone(true)

clone will have the cloned element's data and event handlers.

But the one created inside the loop does not contain an event handler.

And event delegation won't work as you are delegating the click .minus_sign

to a button that is also dynamically created.



You have to delegate your event handler to a static element like

$(document).on('click', '.buttons .minus_sign', function() {
    var parent_id = $(this).parent().attr('id');
    $("#"+parent_id).remove();
    $("input[name='"+parent_id+"']").remove();              
});

      

BTW, Since the method remove()

returns the removed item, you can do above like

 $(document).on('click', '.buttons .minus_sign', function() {
    var parent_id = $(this).parent().remove().attr('id');
    $("input[name='"+parent_id+"']").remove();              
});

      

0


source







All Articles