JavaScript: cloneNode vs importNode

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 01:37:46

问题


I noticed in some code samples to seemingly different ways to clone a DOM node and append it to an existing element:

element.appendChild(something.cloneNode(true));
element.appendChild(document.importNode(something, true));

Both have the effect of copying a node. The second version seems more verbose, and implies that the copy is actually somewhere concrete first, though it still needs to find a proper home. However, it is used by MDN and a few other as an illustration of using the template tag. Elsewhere they go for the simpler clodeNode option.

The question is: what is the benefit to using importNode over cloneNode?


回答1:


In DOM3 and earlier, importNode was for copying nodes from other documents, cloneNode for copying within the same document. But browsers don't enforce that, so in the latest DOM standard cloneNode can be used to copy from a different document. When using DOM in other contexts, stick with the DOM3 rules.



来源:https://stackoverflow.com/questions/43167537/javascript-clonenode-vs-importnode

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