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