将所有子节点复制到其他元素的本机方法
我必须更改 XML 的“未知”内容。结构和内容本身是有效的。 Original
<blabla foo="bar">
<aa>asas</aa>
<ff>
<cc>
<dd />
</cc>
</ff>
<gg attr2="2">
</gg>
...
...
</blabla>
就
<blabla foo="bar">
<magic>
<aa>asas</aa>
<ff>
<cc>
<dd />
</cc>
</ff>
<gg attr2="2">
</gg>
...
...
</magic>
</blabla>
这样,直接在文档根节点 (document.documentElement) 下添加一个子节点,并将“原始”子节点“推送”到该节点下。 这里必须用普通的 javascript (ecmascript) 来完成。
现在的想法是
// 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);
如何执行 /* */ 步骤?或者也许有人有更好的解决方案来实现理想的结果?
先感谢您!
回答: maerics 的解决方案非常有效。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样的东西应该适用于纯 DOM 和 ECMAScript:
Something like this should work with pure DOM and ECMAScript: