0

html:

<div class="testSpanDiv"></div>

javascript:

  $(document).ready(function () {
      $('.testSpanDiv').append('<span id="testSpan">Hello</span>');
  }

  $('#testSpan').on('click', function(){
      $(this).parent().remove();
  });

Event is not firing while giving a click to span element added dynamically. Event is firing if span element is statically added to the html. Can you give any suggestion over it.

I tried like below also, but not working.

  $('#testSpan').on('click', '.testSpanDiv', function(){
      $(this).parent().remove();
  });
Sandeep sandy
  • 387
  • 7
  • 14

3 Answers3

0

You need to use like this:

 $('.testSpanDiv').on('click', '#testSpan', function(){
  // ^^ parent div             ^^ element in which you want to bind the function
      $(this).parent().remove();
 });
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

your syntax error try this way

$(document).ready(function () {
      $('.testSpanDiv').append('<span id="testSpan">Hello</span>');


   $('#testSpan').on('click', function(){
      $(this).parent().remove();
  });
  });

https://jsfiddle.net/7x8jbLpt/

Lalji Tadhani
  • 14,041
  • 3
  • 23
  • 40
0

You can delegate the event from body

Also note there are some syntax error in your code

 $(document).ready(function () {
      $('.testSpanDiv').append('<span id="testSpan">Hello</span>');
  })

  $('body').on('click', '#testSpan', function(){
      alert("Hello")
  });

JSFIDDLE

brk
  • 48,835
  • 10
  • 56
  • 78