amy burgess amy burgess - 4 years ago 89
HTML Question

How to remove a div that has been created using .append() in jquery?

I would like to remove the div created using .append()

Example:
HTML

<input id="type_ingd" type="text">
<button class="btn btn-primary" id="add_ingd">
Add
</button>

<div class="text-left ingd-cont">
<div class="btn-group incl-ingd">
<div type="button" class="btn btn-default">
Rooms <i class="fa fa-close"></i>
</div>
</div>
<div class="btn-group incl-ingd">
<div type="button" class="btn btn-default">
Mansions <i class="fa fa-close"></i>
</div>
</div>
</div>


JS

$("#add_ingd").on('click', function(e) {
var ti = $('#type_ingd').val();
$( ".ingd-cont" ).append( '<div class="btn-group incl-ingd"><button type="button" class="btn btn-default">'+ti+' <i class="fa fa-close"></i></button></div>' );
});

$("i.fa-close").on('click', function(e) {
removeIngd(this);
});
function removeIngd(thiscont) {
$(thiscont).closest('div.incl-ingd').remove();
var iiv = $(".incl-ingd:visible").length;
if (iiv == 0){
$("#find-recp-btn").attr('style', 'display:none;');
}
}


First, I try to input a word (ex: kitchen)then click the
Add
button.

Then the word will append inside the
ingd-cont
.

And the problem is when I click the
fa-close
of the word it does not removed..

I'm not sure if this is possible but if it is, please help me out :)

Answer Source

The problem is with your selector $("i.fa-close").on('click', function(e) {...}); which does not catch events on elements, which were dynamically added.

The selector can be changed to into this to catch also the dynamically added elements:

$(".ingd-cont").on('click', 'i.fa-close', function(e) {
  removeIngd(this);
});

Here is working example. I adjusted your code slightly to make it working properly ;)

$("#add_ingd").on('click', function(e) {
  var ti = $('#type_ingd').val();
  $( ".ingd-cont" ).append( '<div class="btn-group incl-ingd"><div type="button" class="btn btn-default">'+ti+' <i class="fa fa-close">X</i></div></div>' );
});

$(".ingd-cont").on('click', 'i.fa-close', function(e) {
  removeIngd(this);
});
function removeIngd(thiscont) {
  $(thiscont).closest('div.incl-ingd').remove();
  var iiv = $(".incl-ingd:visible").length;
  if (iiv == 0){
    $("#find-recp-btn").attr('style', 'display:none;');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="type_ingd" type="text">
<button class="btn btn-primary" id="add_ingd">
  Add
</button> 

<div class="text-left ingd-cont">
  <div class="btn-group incl-ingd">
    <div type="button" class="btn btn-default">
      Rooms <i class="fa fa-close">X</i>
    </div>
  </div>
  <div class="btn-group incl-ingd">
    <div type="button" class="btn btn-default">
      Mansions <i class="fa fa-close">X</i>
    </div>
  </div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download