user3396033
user3396033

Reputation: 15

how to remove inserted link using jquery

Below is the sample code

here when i click the link, 'div' is added to the main box but when i click div(.sub_box) its not remove

How i can activate 'div' click after adding

<div class="main_box">
<a href="#" class="add">add box</a>
<div class="sub_box">remove box</div>
</div>


$('.main_box .add').click(function () {
    $('.main_box').append('<div class="sub_box">remove box</div>');
});

$('.main_box div').click(function () {
    $(this).remove();
});

Upvotes: 0

Views: 26

Answers (2)

Sudharsan S
Sudharsan S

Reputation: 15393

You added the sub_box class dynamically so use event delegation in jquery

$('.main_box').on('click' '.add', function () {
   $(this).append('<div class="sub_box">remove box</div>');
});

$('.main_box').on('click','.main_box div',function () {
            $(this).remove();
});

Upvotes: 0

Felix
Felix

Reputation: 38102

You need to use event delegation here since your div has been appended to the DOM dynamically:

$('.main_box').on('click','.main_box div',function () {
    $(this).remove();
});

Upvotes: 2

Related Questions