How to destroy dynamically created DOM element using jquery?

I am creating a dynamic range inside a range with some form elements and creating a button with a data id inside the same dynamically using jquery append on the #add_more range. I want to remove that specific interval when a button of that range is clicked.

Step 1.

<input type="button" value="Add More" id="more_size">
<span id="add_more"></span>

      

2. Click the "Add More" button: -

<input type="button" value="Add More" id="more_size">
<span id="add_more">
    <span id="1001"><input type="text" name="price[]">
    <button data-id="1001" type="button">X</button></span>
</span>

      

3. When button with id 1001 is clicked, the span with id 1001 should be removed using jquery remove ().

<input type="button" value="Add More" id="more_size">
<span id="add_more"></span>

      

I am new to Stack Overflow. This is the best way to explain my problem.

+3


source to share


3 answers


use the following:

function removeSpan(spanId) {
   $("#"+spanId).remove();
}

      

call removeSpan

using spanid

.



to pass the id, you can do the following:

$('button').on('click',function(){
     id = $(this).data('id');// since your data-id and span id are same
     removeSpan(id);
});

      

or during creation it is possible to add a function and pass the id you assigned.

+1


source


have a common class on the button get data-id of the clicked button ...

<span id="add_more">
  <span id="1001"><input type="text" name="price[]">
  <button data-id="1001" type="button" class='remove_class'>X</button></span>
</span>

      

add an event listener button to this button using the (remove_class) class.



$(document).on('click','.remove_class',function(){
     id = $(this).data('id');
     $('#'+id).remove();
});

      

you can add any range of numbers. using a class to get the currently pressed button is very easy.

+1


source


You can just use the method prev()

:

$("#add_more").on("click", "button", function() {
  $(this).prev().remove();
});

      

If you also want to remove the button, you can use addBack()

:

$("#add_more").on("click", "button", function() {
 $(this).prev().addBack().remove();
});

      

I am not suggesting manually generating attributes id

, data-*

etc. for this purpose (if above is the only purpose of generating them), often you can avoid this by using a generic class and correct methods.

0


source







All Articles