natsu1627 natsu1627 - 1 year ago 148
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

and my script

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

But this doesn't work

Answer Source

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

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