0

i want to add li elements it´s work fine, but the remove dosen´t work for the new elements. I had three li Elements at the start, for that the remove function work´s.

With my "add" Function i create the Li Elements with the same class, why it doesent work for the new one ?

http://jsfiddle.net/3c96gduL

$(document).ready(function(){
    $("#add_li").click(function (){
        $("ol").append("<li>" + $("input").val() + "<a href=\"#\" class=\"remove\">X</a></li>");
    });
    $("#remove_li").click(function(){
        $("li:last").remove();
    });
    $(".remove").click(function(){
        $(this).parents('li').remove();
    });

    var log = $('.remove');
    console.log(log);
    console.log(jQuery);    

});
ToyRobotic
  • 557
  • 10
  • 30

1 Answers1

4

you need to use event delegation for attaching event to dynamically added dom.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$("ol").on('click','.remove',function(){
    $(this).parents('li').remove();
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125