natsu1627
natsu1627

Reputation: 27

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

Upvotes: 1

Views: 468

Answers (2)

Roxoradev
Roxoradev

Reputation: 893

Try with this:

var html = $("#parent").html();
var i = 1;

$("button").on("click",function(){
  i++;
  $("#parent").append(html.replace('id="child_1"','id="child_' + i + '"'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
   <div id = "child_1">
       <div><input type = "text"></div>
       <div><input type = "text"></div>
       //several inputs and divs
   </div>
</div>
<button>Click</button>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

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

Upvotes: 2

Related Questions