Question

I'm making a simple FileManager, but I don't know what is wrong with my code, I used several times the remove() and/or detach() functions of jQuery, but this time it isn't removing the selected node from the rest of the grid.

The code is the following:

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
    $(".excluir").click(function(){
        $(this).remove();
    });

    $("#novo").click(function(){
        $("#gradearquivos").append("<div class=\"miniatura\"><button class=\"excluir\">X</button></div>");
    });
});
</script>

The append() is working correctly, creating the file thumbs, but the remove() isn't! What did I do wrong this time? PS: jsFiddle

Was it helpful?

Solution

You need to use event delegation ,because the buttons are created dynamically.The elements are not present in the time of event binding. Also you need to select the parent('.miniatura') otherwise it will only remove the close icon not the .miniatura div

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
    $("#gradearquivos").on('click',".excluir",function(){
        $(this).parent('.miniatura').remove();
    });

    $("#novo").click(function(){
        $("#gradearquivos").append("<div class=\"miniatura\"><button class=\"excluir\">X</button></div>");
    });
});
</script>

Fiddle Demo

OTHER TIPS

You need event delegation using jQuery on() for dynamically added elements. The elements having class excluir are added by javascript and are not present in DOM at the time click is binded. So the click event in not binded. You probably need to remove the parent element of button being clicked that is element with class miniatura

Live Demo

$(document).on("click", ".excluir", function(){
    $(this).parent('.miniatura').remove();
});

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery doc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top