简体   繁体   中英

Remove dynamically created elements (with separate delete button) using jquery

I'm trying to delete dynamically created elements each with their own delete button. This is the element that gets added with every button click. When the delete button of an element gets clicked I want that specific element to be deleted.

I use the following code to append the element:

$("#addsitem").click(function () {
  $("#holdsitems").append('myFunction');
});

This is how I try to remove it:

$("#item").on("click", "#deleteitem", function() {
    $("#item").remove();
});

I can only delete the elements that haven't been added.

This is all the relevant HTML code (myFunction) of the element:

<div id="item" class="itemdiv">
  <form>
    <div>
      <div id="deleteitem">
        <input type="button" name="Delete Button" value="Delete">
      </div>
    </div>
  </form>
</div>

I'm rather new to jQuery and this is giving me headaches. Would appreciate it lots if someone could help me out!

You can use classes and the command .closest("selector") where this moves up the DOM tree until it finds the first element that matches that selector, you can then remove this.

You shouldn't be adding an id dynamically, unless you are adding an indices so that they are unique.


Demo

 // Add new item on click of add button $("#addsItem").click(function(event) { // Stop submission of form - this is not necessary if you take it out of the form event.preventDefault(); // Append new form item $("#holdsitems").append('<div class="item-wrapper"><button type="button" class="deleteItem" >Delete</button></div>'); }); // Add DYNAMIC click event to class .deleteItem $(document).on("click", ".deleteItem", function() { // Move up DOM tree until first incidence of .item-wrapper and remove $(this).closest(".item-wrapper").remove(); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="item" class="itemdiv"> <form> <div id="holdsitems"> <button id="addsItem">Add Item</button> <div class="item-wrapper"> <button type="button" class="deleteItem">Delete</button> </div> </div> </form> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM