Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Remove() not removing selected node

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

like image 999
Andrey Russo Tragik Avatar asked Feb 11 '26 19:02

Andrey Russo Tragik


1 Answers

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

like image 143
Pranav C Balan Avatar answered Feb 13 '26 15:02

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!