2

This link1 - work

<div class="test">test</div>
<div class="test2"></div>
$('.test2').click(function(){
$('.test2').remove();

This link2 - dont work

<div class="test">test</div>
$('.test').click(function(){
$('body').prepend('<div class="test2"></div>');
});
$('.test2').click(function(){
$('.test2').remove();
});

why ?

5 Answers5

3

try:

$(document).on('click','.test2',function(){
    $('.test2').remove();
});

fiddle

suhailvs
  • 14,937
  • 8
  • 78
  • 88
  • @Ap313 please refer the documetation [event delegation](http://learn.jquery.com/events/event-delegation/) – suhailvs Dec 06 '13 at 06:15
3

You need to use event delegation since it's created on the fly

$(document).on("click",".test2",function(){
    $(this).remove(); //you can use 'this' instead
});
Sterling Archer
  • 20,452
  • 15
  • 77
  • 107
2

Write:

$('.test').click(function(){
    $('body').prepend('<div class="test2"></div>');
    $('.test2').click(function(){
        $('.test2').remove();
    });
});

DEMO here.

OR

$('.test').click(function () {
    $('body').prepend('<div class="test2"></div>');
});
$(document).on('click','.test2',function () {
    $('.test2').remove();
});

DEMO here.

Hiral
  • 14,954
  • 11
  • 36
  • 57
2

Using the live click, it is working fine. Refer the fiddle update

http://jsfiddle.net/AzW7a/11/

$('.test').click(function(){
    $('body').prepend('<div class="test2"></div>');
});
$('.test2').live('click',function(){
    $('.test2').remove();
});
renuka
  • 509
  • 1
  • 5
  • 11
2
$(document).on('click','.test2',function(){
    $('.test2').remove();
});

Reason:Why the above code works and yours does not?

1.You are dynamically adding elements.In simpler words,the element you appended did not exist when DOM was loaded.

2.You need to assign Event Delegation for any future addition of elements.The method that we usually use like .click(...) , .on(..) etc only applies to the elements that are currently in the DOM.

3.This is how you provide Event Delegation.

 $(document).on('keyup', '.class', function(){.........})
Community
  • 1
  • 1
HIRA THAKUR
  • 15,044
  • 14
  • 47
  • 82