Reputation:
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 ?
Upvotes: 2
Views: 109
Reputation: 17757
$(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(){.........})
Upvotes: 2
Reputation: 549
Using the live click, it is working fine. Refer the fiddle update
$('.test').click(function(){
$('body').prepend('<div class="test2"></div>');
});
$('.test2').live('click',function(){
$('.test2').remove();
});
Upvotes: 2
Reputation: 15709
Write:
$('.test').click(function(){
$('body').prepend('<div class="test2"></div>');
$('.test2').click(function(){
$('.test2').remove();
});
});
OR
$('.test').click(function () {
$('body').prepend('<div class="test2"></div>');
});
$(document).on('click','.test2',function () {
$('.test2').remove();
});
Upvotes: 2
Reputation: 22425
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
});
Upvotes: 3