简体   繁体   中英

Clone <div> and change id

How can I using javascript make clone of some <div> and set his id different from original. Jquery also will be nice.

var div = document.getElementById('div_id'),
    clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "some_id";
document.body.appendChild(clone);

Use it:

JQuery

var clonedDiv = $('#yourDivId').clone();
clonedDiv.attr("id", "newId");
$('#yourDivId').after(cloneDiv);

I had the same problem. I've solved that by setting a counter and appending it to the ID. Hope it helps you too:

<script type="text/javascript">
     var counter = 1; //Set counter

function clone(sender, eventArgs) {
     var $row = $('#yourID');

     var $clone = $row.clone(); //Making the clone                      
     counter++; // +1 counter

     //Change the id of the cloned elements, append the counter onto the ID 
     $clone.find('[id]').each(function () { this.id += counter });
}
</script>

jQuery have method clone()

var original = $("#original");
var newClone = original.clone();

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