-1

I have a code where i appending to div some html over JQuery like

$("#divId").append("<div class='click' data-id='id'></div>");

and I want to acces by click appended div like this

$(".click").click(function(){
var id = $(this).attr('data-id');
alert(id);
});

but when I click, nothink happens, is there some solution for this? Thanks!

koca79331
  • 321
  • 4
  • 19
  • 2
    possible duplicate of [Jquery click event not working after append method](http://stackoverflow.com/questions/15420558/jquery-click-event-not-working-after-append-method) – IROEGBU Aug 21 '15 at 22:30
  • possible duplicate of http://stackoverflow.com/questions/32144892/jquery-dynamic-form-event-on-dynamic-field/32145552#32145552 – J Santosh Aug 21 '15 at 22:35

1 Answers1

0

You need to use event Delegation.

$("body").on('click', '.click', function(){
   var id = $(this).attr('data-id');
   alert(id);
});

As the events are only bound for already existing elements on the page. but in your case you are dynamically appending the elements.

body can also be substituted to the closest ancestor that contains these elements.

$("#divId").on('click',

Check Fiddle

Sushanth --
  • 55,259
  • 9
  • 66
  • 105