FoamyGuy FoamyGuy - 4 months ago 5
HTML Question

Moving <li> to another list need to update click listeners

See an example here:

I have two

s. Clicking an item in the second one will move that item to the first one.

In the first list each
contains a
with the class
. when this span gets clicked it should remove the item from the list.

This is working correctly except for when you move an item from the second list into the first list and then try to delete it. Once the delete-btn span of a moved item gets clicked it seems to still be registering the click listener for the second list even though it is no longer in the second list.

My click listener is applied like this:

$(".second li").click(function(){
$(".first").append($(this).append(' <span class="delete-btn">[ X ]</span>'));

after the li is moved and then the delete-btn span is clicked it calls this click listener even though the
no longer is a decedent to the

How can I update the click listener when I move the
from the second list to the first so that the delete button listener will work after the item has been moved.


That's because you're attaching the click listener to the li's themselves. When the li is moved, it still has the click event listener and just duplicates itself. You should instead attach the event listeners to the lists and have it listen for clicks on child lis like so:

$(".second").on('click', 'li', function(){
  $(".first").append($(this).append(' <span class="delete-btn">[ X ]</span>'));

$(".first").on('click', '.delete-btn', function(){
  float: left;

.second li{
  background-color: #BABABA;
<script src=""></script>
<ul class="first">
<li>item 1 <span class="delete-btn">[ X ]</span></li>
<li>item 2 <span class="delete-btn">[ X ]</span></li>

<ul class="second">
<li>item 3</li>
<li>item 4</li>