user2104409
user2104409

Reputation:

Div not removed by click jquery?

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

Answers (5)

HIRA THAKUR
HIRA THAKUR

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

renuka
renuka

Reputation: 549

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();
});

Upvotes: 2

codingrose
codingrose

Reputation: 15709

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.

Upvotes: 2

Sterling Archer
Sterling Archer

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

suhailvs
suhailvs

Reputation: 21740

try:

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

fiddle

Upvotes: 3

Related Questions