natsu1627 natsu1627 - 5 months ago 22
HTML Question

Append element using jquery selector

I need to recreate and append my template div to the parent div on button click and this can be done multiple times

<div id = "parent">
<div id = "child_1">
<div><input type = "text"></div>
<div><input type = "text"></div>
//several inputs and divs
</div>
</div>


and my script

//on button click event
var template = $("#parent").children().last();
template.attr("id","child_2"); //just a sample of dynamic id
$("#parent").append(template);


But this doesn't work

Answer

You need to clone() a copy of the child before you append it, otherwise you just put the current element back in its original position.

var template = $("#parent").children().last().clone();

Working example