40

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Timofey Trofimov
  • 1,134
  • 3
  • 12
  • 26
  • 2
    possible duplicate of [How to clone element with new id?](http://stackoverflow.com/questions/6993373/how-to-clone-element-with-new-id) and [Quickest way to clone element and autioincrement id (jquery)](http://stackoverflow.com/questions/3274156/quickest-way-to-clone-element-and-autioincrement-id-jquery) and [many more](http://stackoverflow.com/search?q=jquery+clone+element+change+id) -- please use the search before you ask a new question. – Felix Kling Aug 16 '12 at 10:26
  • Really sorry. Guess I dont formed question in the search field correctly. – Timofey Trofimov Aug 16 '12 at 10:44

4 Answers4

133
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);
Sergii Stotskyi
  • 5,134
  • 1
  • 22
  • 21
8

Use it:

JQuery

var clonedDiv = $('#yourDivId').clone();
clonedDiv.attr("id", "newId");
$('#yourDivId').after(cloneDiv);
Mateusz Rogulski
  • 7,357
  • 7
  • 44
  • 62
4

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>
YakovL
  • 7,557
  • 12
  • 62
  • 102
Ryan Gavin
  • 689
  • 1
  • 8
  • 22
-2

jQuery have method clone()

var original = $("#original");
var newClone = original.clone();
derki
  • 620
  • 3
  • 7