4

here i'm able to remove box100 and box200 when clicked but not able to remove box1-box5 after appending it to the list. How do I select the appended elements?

https://jsfiddle.net/uhmgj8ky/4/

html
  <ul>
  <li class='list'>remove box100</li>
  <li class='list'>remove box200</li>
  </ul>
  <div class='box' box='box1'>add box1</div>
  <div class='box' box='box2'>add box2</div>
  <div class='box' box='box3'>add box3</div>
  <div class='box' box='box4'>add box4</div>
  <div class='box' box='box5'>add box5</div>

css
.box{
  height:50px;
  width:50px;
  border:2px solid blue;
  display: inline-block;
}
ul li{
    height:50px;
  width:50px;
  border:2px solid blue;
  display: inline-block;
  margin-right: 1px;
}

jquery
$('.box').on('click', function(){
    var txt = $(this).attr('box');
    $('ul').append("<li class='list'>remove "+txt+"</li>");
});

$('.list').on('click', function(){
    $(this).remove();
});
1
  • As a sidenote, box is not a valid attribute, you should be using data-box Commented Mar 19, 2016 at 20:45

1 Answer 1

10

You should use event delegation

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. Both 

on()

 and 

delegate()

functions allow us to perform event delegation.

  


added a container class

 <ul>
  <li class='list'>remove box100</li>
  <li class='list'>remove box200</li>
  </ul>
<div class="box-container">
  <div class='box' box='box1'>add box1</div>
  <div class='box' box='box2'>add box2</div>
  <div class='box' box='box3'>add box3</div>
  <div class='box' box='box4'>add box4</div>
  <div class='box' box='box5'>add box5</div>
</div>

   $('.box-container').on('click',".box", function(){
     var txt = $(this).attr('box');
    $('ul').append("<li class='list'>remove "+txt+"</li>");
    });

     $('ul').on('click','.list', function(){
     $(this).remove();
     });

Update https://jsfiddle.net/uhmgj8ky/6/

For more on event delegation ,see video

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.