PDA

View Full Version : Resolved Can you append the same node multiple times?



jlizarraga
10-27-2008, 11:04 PM
Hi all,

Simple quick question: If I create "oChild" with createElement, and then use appendChild to add it to "oParent", can I append oChild to a different element later, so that both parents have an instance of oChild?

And if so, can I also attach multiple instances of oChild to oParent?

Thanks!

magicyte
10-27-2008, 11:06 PM
I'm pretty sure you can.

-magicyte

jscheuer1
10-28-2008, 05:45 PM
In testing, no:


window.onload = function(){
var el = document.createElement('div');
el.appendChild(document.createTextNode('Hi'));
for (var i = 10; i > 0; --i)
document.body.appendChild(el);
};

will append only one node to the body. However, if you clone the node:


window.onload = function(){
var el = document.createElement('div');
el.appendChild(document.createTextNode('Hi'));
for (var i = 10; i > 0; --i)
document.body.appendChild(el.cloneNode(true));
};

That works.

If you do this though, be careful. If you set an id for the node or anything that later may need to be unique for further processing, there will be problems if and when that unique feature is attempted to be used in that processing.

jlizarraga
10-28-2008, 05:56 PM
Thanks John!

Jesdisciple
10-28-2008, 06:00 PM
EDIT: Oops. I'm a little late.


appendChild
Adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed.


If child is a reference to an existing node in the document, appendChild moves it from its current position to the new position (i.e. there is no requirement to remove the node from its parent node before appending it to some other node).

This also means that a node can't be in two points of the document simultaneously. So if the node already has a parent, it is first removed, then appended at the new position.

Microsoft presumably follows the standard as well, but they don't explicitly say so (http://msdn.microsoft.com/en-us/library/ms535934(VS.85).aspx).