Native way to copy all child nodes to an other element

青春壹個敷衍的年華 提交于 2019-11-28 12:26:37

问题


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!

Answer: The solution by maerics works perfectly.


回答1:


Something like this should work with pure DOM and ECMAScript:

var blabla = mymagicdoc.documentElement
  , magic = mymagicdoc.createElement("magic");
while (blabla.hasChildNodes()) {
  magic.appendChild(blabla.removeChild(blabla.firstChild))
}
blabla.appendChild(magic);


来源:https://stackoverflow.com/questions/3066427/native-way-to-copy-all-child-nodes-to-an-other-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!