setting parent node in javascript

不想你离开。 提交于 2019-12-10 11:48:54

问题


when Im cloning an object in javascript by doing object.cloneNode(true) the parentNode is null in the new copy. Im trying to set it but with no success. my code look like this:

old_DataRoot = DataRoot.cloneNode(true);
old_DataRoot.parentNode=DataRoot.parentNode.cloneNode(true);

also tried:

    old_DataRoot = DataRoot.cloneNode(true);
    old_DataRoot.parentNode.appendChild(DataRoot.parentNode.cloneNode(true));

both options give me "old_DataRoot.parentNode is null or not an object" what am I doing wrong?

thanks alot, Yoni.


回答1:


If you're trying

to make a backup of the original DataRoot in order to recover it later.

then consider

// Backup
var DataRootBackup = {
    nodes: DataRoot.cloneNode(true),
    parent: DataRoot.parentNode
};

// Restore
DataRootBackup.parent.appendChild( DataRootBackup.nodes );



回答2:


Yes, that's true, parentNode is a read-only property.

In your second case you need know that only one of the nodes is attached to the DOM. It's dataRoot which still has the parentnode, the result of the clone (which you called old_DataRoot) is unattached:

dataRoot.parentNode.appendChild(newDataRoot = dataRoot.cloneNode(true));



回答3:


Is this what you're trying to do?

old_DataRoot = DataRoot.cloneNode(true);
DataRoot.parentNode.appendChild(old_DataRoot);


来源:https://stackoverflow.com/questions/12957267/setting-parent-node-in-javascript

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