• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2758
  • Last Modified:

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

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

Open in new window

0
drew22
Asked:
drew22
  • 2
  • 2
1 Solution
 
David S.Commented:
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?
0
 
drew22Author Commented:
>>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
0
 
David S.Commented:
Yes, but the problem is only if both elements are part of the document. If only one of them is, then it doesn't matter.
0
 
drew22Author Commented:
right, the clone isn't yet part of the document. forgot about that
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now