Pauljh wrote:
Hi All,
I have a web page which builds a hidden table, as (based on certain
criteria) people can have multiple version of this table, not a
problem. But I need each table to have a unique id (that I know before
hand) and unique id's for each element (the id="" tags are assigned in
the original hidden table).
So I can't used CloneNode as this keeps the id's, can someone point
me in the right direction for a script which will copy nodes +
attributes (as far down as they go) (for any object type, as I might
change it from a table to a div in the future) and append a passed
variable to each id (if id!=null).
Clone the node, then use a recursive function to change all the child
IDs.
e.g.
<script type="text/javascript">
function cloneEl(oldID, newID) {
var el = document.getElementById(oldID);
var newEl = el.cloneNode(true);
var oldPattern = oldID + '_';
var newPattern = newID + '_';
newEl.id = newID;
modIDs(newEl, oldPattern, newPattern);
el.parentNode.insertBefore(newEl, el.nextSibling);
}
function modIDs(node, oldPattern, newPattern) {
var child, nodes = node.childNodes;
for (var i=0, len=nodes.length; i<len; i++){
child = nodes[i];
if ('string' == typeof child.id){
child.id = child.id.replace(oldPattern, newPattern);
}
if (child.childNodes && child.childNodes.length){
modIDs(child, oldPattern, newPattern);
}
}
}
// Just for debug
function showID(e){
var el = e.target || e.srcElement;
if (el.id) alert(el.id);
}
</script>
<body onclick="showID(event);">
<div id="divA">divA_01
<div id="divA_div01">divA_02
<span id="divA_span01">Span 01</span>
</div>
<div id="divA_div03">divA_03
<span id="divA_span02">Span 02</span>
<span id="divA_span03">Span 03</span>
<span id="divA_span04">Span 04</span>
</div>
</div>
<button onclick="cloneEl('divA', 'divB');">Clone it</button>
</body>
--
Rob