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
  • 931
  • 1
  • 14
  • 33

1 Answers1

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

Use event delegation method for dynamically created elements.

RGS
  • 5,131
  • 6
  • 37
  • 65
  • 3
    You should really show him the *good way* to use event delegation : closest static parent. `$('.addmenow').on('click', '.removemenow', function(){})` – Karl-André Gagnon Jul 25 '14 at 17:07
  • 1
    Awesome, thank you! Just tried this and it worked perfectly. I'll be able to accept this in 8 minutes. Thanks again! – user3007294 Jul 25 '14 at 17:10