1

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.