简体   繁体   中英

Clone a div and make ID's of it it's children to be unique using javascript

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.

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);

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