1

Does anyone knows why I cannot remove the letter B in the list?

Steps to reproduce:

  1. click on "Add to list" button
  2. letter B is added to the list
  3. click on letter B in the list to remove
  4. letter B is not removed from list
  5. click on letter C or A
  6. letter C or A is removed from list

HTML:

<button id="add">Add to list</button>
<ol>
    <li>A</li>
    <li>A</li>
    <li>A</li>
</ol>

Jquery:

$(document).ready(function(){

    $("ol").append("<li>C</li");

    $("#add").click(function(){
        $("ol").append("<li>B</li>");
    });

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

Here you have the sample in the jsfiddle.

Best regards.

Alba
  • 25
  • 1
  • 7

2 Answers2

3

This is happening because the event handler is lost when you append a new element. You can refer to the solution in the following answer to see how to do it correctly. jQuery how to bind onclick event to dynamically added HTML element

Here is your JSFiddle
 https://jsfiddle.net/qsh4pb5r/1/
Community
  • 1
  • 1
Pranava Sheoran
  • 519
  • 2
  • 26
1

You can use event delegation for dynamic item

Try like this

$(document).on("click","li",function(){
    $(this).remove();
});

JSFIDDLE

Anik Islam Abhi
  • 24,324
  • 8
  • 52
  • 74