drew22
asked on
avoiding duplicate ids with cloneNode
I like to use cloneNode instead of dynamically building up html via DOM methods. However, grabbing the element via getElementBy Id and then clone it, you have duplicate ids.
I usually use the technique in ex 2, but I was wondering if there is anything wrong with the way in ex 1 where I grab the element by id, remove the id attribute, clone the element, set the id attribute back again
I usually use the technique in ex 2, but I was wondering if there is anything wrong with the way in ex 1 where I grab the element by id, remove the id attribute, clone the element, set the id attribute back again
<!-- this div just holds templates for cloning -->
<div id="tpl_holder" style="display:none">
<div "confirm_tpl">
<-- bunch of html here -->
</div>
</div>
// ex 1:
var confirm_tpl = getElementByID("confirm_tpl");
confirm_tpl.removeAtrribute("id");
var confirm = confirm_tpl.cloneNode(true);
confirm_tpl.setAtrribute("id","confirm_tpl");
// ex 2:
var remove_div = getElementsByClassName("commands",getElementByID("tpl_holder"),"div")[0].cloneNode(true);
Why remove the ID of the element before cloning it? Why not just change the ID of the clone before adding it as a child of an element in the document?
ASKER
>>Why not just change the ID of the clone before adding it as a child
because before you change the id of the clone you will have 2 elements with the same id and element ids must be unique
because before you change the id of the clone you will have 2 elements with the same id and element ids must be unique
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
right, the clone isn't yet part of the document. forgot about that