user3489502 user3489502 - 2 months ago 6
HTML Question

How to dynamically add content from one div to another onClick with Javascript

How do I add the content from

iteminitial
to
item
each time I click the
additem
button? I don't get why my appendChild doesn't work.

See plunker: https://plnkr.co/edit/Z223520OyRfv9XyzcNTu

html:

<div id="iteminitial">
<div class="row" style="padding: 0.5em 0 0.5em 0.5em">
<div class="col-sm-6" >
<input class="form-control" type="text" name="number[]">
</div>
<div class="col-sm-6" >
<input class="form-control" type="text" name="period[]">
</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 item" onClick="additem();">
</div>


js:

function additem(){

var newitem = document.getElementById('item');
var initialitem = document.getElementById('iteminitial');

newitem.appendChild(initialitem);
}

Answer

It works nicely, but it's just moving the initialitem into item. What you need to do is clone the initialitem and then add it to item. Like this: https://plnkr.co/edit/Z4l8jmdEqsrBzbyyIOHj?p=preview

function additem(){
    var newitem = document.getElementById('item');
    var initialitem_clone = document.getElementById('iteminitial').cloneNode(true);
    console.log(newitem)
    newitem.appendChild(initialitem_clone);
}