Kal
Kal

Reputation: 43

Removing dynamically generated elements, when clicking on an element within itself in jQuery?

How can I remove a dynamically generated block of elements when clicking the button inside of it?

function controlContent(target, trigger) {
    //this will add a new div to target which is an existing html element
    $(trigger).on("click", () => {
        $(target).append(`
            <div class="dynamic-container">
                <button class="remove-btn">Remove the div I am inside</button>
            </div>
        `)
    }

    //this should remove the div that was added when I click the remove button
    $(target).on("click", ".remove-btn", () => {
        $(this).closest(".dynamic-container").remove();
    }
}

Upvotes: 1

Views: 113

Answers (2)

Evik Ghazarian
Evik Ghazarian

Reputation: 1791

FIRST: you should use $(document).on("click", target, function(){...} for dynamically generated elements

SECOND: As simple as parent()

$(document).on("click", target, function(){
  $(this).parent().remove();
 });

EXAMPLE:

$(".button1").on("click", function(){
$(".generatedbuttons").append('<div class="green"><button class="button2">Click me to remove me and my parent</button></div>');
});
$(document).on("click", ".button2", function(){
  $(this).parent().remove();
});
.button1 {
display:block;
float: left;
}
.green {
padding: 10px;
background-color: green;
display: block;
float: left;
clear: both;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="button1">Click me to generate buttons</button>

<div class="generatedbuttons">
</div>

Upvotes: 3

SOEqualsLigma
SOEqualsLigma

Reputation: 74

use normal function and also use dynamic click listener so you don't need to create a new event lister every time.

$(document).on('click', '.remove-btn', function(){
    $(this).closest(".dynamic-container").remove();
})

Upvotes: 3

Related Questions