Jump to content


Javascript: cloneNode


1 reply to this topic

#1 BlazeForc3

    Young Padawan

  • Members
  • Pip
  • 62 posts
  • Location:Australia

Posted 06 September 2007 - 12:23 AM

I am using the javascript function cloneNode to duplicate a block of html and all of its child nodes. To explain my problem i will give a couple of examples.

Say I am duplicating this block of html:

<div class="style1" id="a">
	<div class="style2"><div class="style3" id="b"></div></div>
</div>

and my javascript code is:

newNode = document.getElementById('a').cloneNode(true);

That all works fine so I end up with two copies of the above html both have the same id's, now not only is it incorrect html to have two id's the same it is also a requirement for what i am doing that the id's need to be different as i want to refer to them seperately.

So I am able to modify the node with id 'a' easily enough by doing:

newNode.setAttribute('id', 'c');

But how do I modify the node with id 'b' without changing both instances of node 'b' to the new id. I tried doing this but got an error and no result:

newNode.firstChild.firstChild.setAttribute('id', 'd');

Any ideas?

Edited by BlazeForc3, 06 September 2007 - 12:24 AM.


#2 rc69

    PHP Master PD

  • P2L Staff
  • PipPipPipPip
  • 3,827 posts
  • Gender:Male
  • Location:Here
  • Interests:Web Development

Posted 06 September 2007 - 01:07 PM

newNode.id = 'c';
newNode.childeNodes[0].childNodes[0].id = 'd';
Check out quirksmode.org sometime. It'll be a little hard to find what you want there, so i'd google it (then it'll still be hard).





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users