-->

[removed] cloneNode vs importNode

2019-09-07 14:47发布

问题:

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.