user3489502 user3489502 - 2 months ago 7
HTML Question

How to dynamically remove content from a div after it has been appended with Javascript

How can I remove any of the items that were added previously using Javascript append? I get the 'Node was not found' error.

See my plunker: https://plnkr.co/edit/CWOxWh3SL5RBFmgJIiwS

html:

<div style="display:none">
<div id="iteminitial">
<div class="row" style="padding: 0.5em 0 0.5em 0.5em">
<div class="col-sm-4" >
<input class="form-control" type="text" name="number[]">
</div>
<div class="col-sm-4" >
<input class="form-control" type="text" name="period[]">
</div>
<div class="col-sm-4" >
<input class="btn btn-default" type="button" value="Remove item" onClick="removeitem();">
</div>
</div>
</div>
</div>


<div id="item">

</div>


<div class="row" style="padding: 0.5em 0 0.5em 0.5em">
<input class="btn btn-default" type="button" value="Add another item" onClick="additem();">
</div>


js:

function additem(){

var newitem = document.getElementById('item');
var initialitem_clone = document.getElementById('iteminitial').cloneNode(true);

newitem.appendChild(initialitem_clone);
}

function removeitem(){

var olditem = document.getElementById('item');
olditem.removeChild(olditem);
}

Answer

Just use element.remove(). Also, you should create unique id attribute values for the cloned items. See the example below:

var itemCount = 1;
    function additem(){
          var newitem          = document.getElementById('item');
          var initialitem_clone      = document.getElementById('iteminitial').cloneNode(true);
          //make the id value unique
          initialitem_clone.id = 'item_'+itemCount++;
          newitem.appendChild(initialitem_clone);
    } 
    
    function removeitem(item){
          //item corresponds to the link that was clicked
          item.parentNode.parentNode.parentNode.remove(); 
    }     
 <div style="display:none">    
    <div id="iteminitial">      
    <div class="row" style="padding: 0.5em 0 0.5em 0.5em">
          <div class="col-sm-4" >
               <input class="form-control" type="text" name="number[]">
          </div>
          <div class="col-sm-4" >
               <input class="form-control" type="text" name="period[]">                   
          </div>  
          <div class="col-sm-4" >
<!-- pass this to the removeitem function -->
               <input class="btn btn-default" type="button" value="Remove item" onClick="removeitem(this);">                   
          </div>              
    </div>
    </div>
    </div>


    <div id="item">     

    </div>


    <div class="row" style="padding: 0.5em 0 0.5em 0.5em">                  
          <input class="btn btn-default" type="button" value="Add another item" onClick="additem();">
    </div>