0

I need to clone a div and after cloning all the elements within the div should have unique ids. I need to do this using javascript only and not jquery.

Can anyone help me please.

Dora
  • 292
  • 3
  • 15
  • Duplicate: http://stackoverflow.com/questions/2331197/clone-a-div-and-change-the-ids-of-it-and-all-its-children-to-be-unique – beeglebug May 31 '12 at 11:30
  • @beeglebug: that's a jquery solition. – KooiInc May 31 '12 at 11:36
  • Just out of curiosity: Why is jQuery no option? Do you want to _understand_ how it is done with vanilla-js (that'd be a valid reason) or is it too hard to include jQuery? – Tharabas May 31 '12 at 11:54
  • there is a conflict of jquery libarsry on my page and i am running out of time, so cant investigate why jquery library is not loading. – Dora May 31 '12 at 12:07

1 Answers1

1

The following code clones an element, uses a recursive function to assign random id's to the cloned element and its children and appends it to the document body. Adjust to your needs. See also this jsfiddle

var someClone = someDiv.clone(true), children = someClone.childNodes;
someClone.id = Math.floor(1000+Math.random()*10000).toString(16);
reId(children);

function reId(nodes){
 for (var i=0;i<nodes.length;(i+=1)){
   var children = nodes[i].childNodes;
   nodes[i].id = Math.floor( 1001+Math.random()*10000 ).toString(16);
   if (children.length){
       reId(children);
   }
 }
}     

document.body.appendChild(someClone);
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • hey KooiInc thanks a lot. This was a great help. It worked for me. – Dora May 31 '12 at 12:54
  • hey KooiInc, nodes[i].id in function reId(nodes) is throwing the follwing error on IE8: "Message: Object doesn't support this property or method". Can u plz tell how to bypass this. On firefox everything working fine. – Dora Jun 01 '12 at 08:24
  • Two things: use `cloneNode` and check the `nodeType`. See the updated jsfiddle @ http://jsfiddle.net/KooiInc/e62sw/ – KooiInc Jun 01 '12 at 08:32
  • I mean that the random generation of ids can lead to two ids that are the same – Stephen C Jun 02 '12 at 07:12
  • Chances of that happening are pretty slim. The jsfiddle I linked to generates a square with two million dots from random number pairs generated by the (JS) `Math.random` method. If `Math.random` had a large chance to generate equal results, a pattern should emerge in the resulting square. But yeah, there's allways a chance. You can build in a check for that, if you don't trust it. – KooiInc Jun 02 '12 at 07:25
  • To satisfy your needs, I forked the original jsfiddle, adding a mechanism to prevent double values. See: http://jsfiddle.net/KooiInc/RuFJp/ – KooiInc Jun 02 '12 at 07:38