[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2500
  • 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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

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