简体   繁体   中英

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

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM