[Solved] Delete HTML elements with JS. WORKING JSFIDDLE [duplicate]


Insert all your code inside a div(it’s easier this way), and use a delegated event handler:

$('#addEnv').click(function() {
  var parentDiv = $('<div/>', {
    class : 'parentDiv',
    html : '<div class="col-sm-5 top10"><div class="input-group"><label class="input-group-addon">Name</label><input id="envName" class="form-control" name="envName" type="text" placeholder="e.g. name1" /></div></div>' +
    '<div class="col-sm-5 top10"><div class="input-group"><label class="input-group-addon">Variable</label><input class="form-control" id="envVar" type="text" name="envVar" placeholder="e.g. var1" /></div></div><div class="col-sm-2 top10"><button type="button" class="btn btn-danger deleteEnv"><span class="fa fa-trash">Delete</span></button></div>'
  });
  $('#envVariablesDiv').append(parentDiv);
});

$('#envVariablesDiv').on('click', '.deleteEnv', function(){
    $(this).parent().parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="addEnv">Add</button>
<div id="envVariablesDiv">

</div>

solved Delete HTML elements with JS. WORKING JSFIDDLE [duplicate]