Copy all childNodes to an other element. In javascript native way.
Posted
by kroko
on Stack Overflow
See other posts from Stack Overflow
or by kroko
Published on 2010-06-18T00:01:08Z
Indexed on
2010/06/18
0:13 UTC
Read the original article
Hit count: 289
Hello
I have to change "unknown" contents of XML. The structure and content itself is valid.
Original
<blabla foo="bar">
<aa>asas</aa>
<ff>
<cc>
<dd />
</cc>
</ff>
<gg attr2="2">
</gg>
...
...
</blabla>
becomes
<blabla foo="bar">
<magic>
<aa>asas</aa>
<ff>
<cc>
<dd />
</cc>
</ff>
<gg attr2="2">
</gg>
...
...
</magic>
</blabla>
thus, adding a child straight under document root node (document.documentElement) and "pushing" the "original" children under that. Here it has to be done in plain javascript (ecmascript).
The idea now is to
// Get the root node
RootNode = mymagicdoc.documentElement;
// Create new magic element (that will contain contents of original root node)
var magicContainer = mymagicdoc.createElement("magic");
// Copy all root node children (and their sub tree - deep copy) to magic node
/* ????? here
RootNodeClone = RootNode.cloneNode(true);
RootNodeClone.childNodes......
*/
// Remove all children from root node
while(RootNode.hasChildNodes()) RootNode.removeChild(RootNode.firstChild);
// Now when root node is empty add the magicContainer
// node in it that contains all the children of original root node
RootNode.appendChild(magicContainer);
How to do that /* */ step? Or maybe someone has a much better solution in general for achieving the desirable result?
Thank you in advance!
© Stack Overflow or respective owner