2

HTML:

<div>
  <ol class='addmenow'>
  </ol>
</div>

jQuery:

$('.item').click(function(){
  $('.addmenow').append("<li class='removemenow'>" +  " " + ($(this).attr('data-value')) + "  </li>")
 })

I can not get this to work:

<script>
  $('.removemenow').click(function(){
    alert('hello')
  })
</script>

Is this because each li element is added AFTER the DOM already loaded? Thus, '.removemenow' in the click event is essentially undefined? I am not getting any errors in the console. The idea is to be able to add an li element to a div and remove it if clicked.

Any insight would be helpful!

Thanks

user3007294
  • 921
  • 13
  • 27

1 Answers1

6
 $('.addmenow').on('click', '.removemenow', function(e){
    alert('hello');
    e.preventDefault();
 });

Use event delegation method for dynamically created elements.

RGS
  • 4,959
  • 5
  • 33
  • 59