3

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?

Manngo
  • 14,066
  • 10
  • 88
  • 110
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode#Notes leads to https://www.w3.org/DOM/faq.html#ownerdoc. When you copy an element from a different DOM, you should use `importNode`, to avoid different DOM behaviors issues. – Kaiido Apr 02 '17 at 11:12
  • @Kaiido How does this differ from `cloneNode`? – Manngo Apr 02 '17 at 11:26
  • only referring on my understanding of previous links, with `importNode`, the new document will make the cloned node his, (sharing its DOM methods and possibly things like NameSpaces etc.), while with `externalDocument.cloneNode()`, the cloned node will still have `externalDocument`'s APIs. – Kaiido Apr 02 '17 at 11:29
  • 2
    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](https://dom.spec.whatwg.org/) cloneNode can be used to copy from a different document. When using DOM in other contexts, stick with the DOM3 rules. – Alohci Apr 02 '17 at 11:39
  • @Alohci If I understand that correctly, the idea _was_ that both will clone a node from the same document, but `importNode` will also clone from a different document. However, now I can choose either? Would you turn that into an answer so that I can accept it? – Manngo Apr 02 '17 at 11:47

1 Answers1

7

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.

Alohci
  • 78,296
  • 16
  • 112
  • 156