cloneNode (W3C DOM Core method)
var clone = node.cloneNode(true);
The example above will make a deep clone of node and save its reference to clone.
node were the HTML
q element in this
<p> <q>Can you copy <em>everything</em> I say?</q> </p>
And we cloned it, then appended the clone to the original node's parent:
var clone = node.cloneNode(true); node.parentNode.appendChild(clone);
We would end up with this:
<p> <q>Can you copy <em>everything</em> I say?</q> <q>Can you copy <em>everything</em> I say?</q> </p>
Actually this example is idealized—the line-break between the first
</q> and second
<q> tags is just for
ease of reading; it hasn't really been created.
Creates a duplicate of this
node, including all attributes and their values (including attributes
which are not explicitly defined but which have a default value in this
document type). The duplicate node has no parent (
null) until it's added to
the document, for example using
If the deep argument is included and has the value
true then the node's sub-tree (if any) will also be
Cloning a sub-tree that is readonly results in a
sub-tree that can be modified (ie. the sub-tree of a cloned node is always
mutable, even if the original was immutable), with the exception that the
children of a cloned
EntityReference are always
Element node also
copies its attributes (including any default attributes), but does not
copy its text unless the deep argument is
The duplicate node.
deep argument is omitted,
Internet Explorer and
where Opera and
Firefox throw an internal error. However
the specification does not explicitly say whether the argument is
required, therefore neither behavior is considered a bug.
Internet Explorer and Firefox 3 cannot append nodes to this document which were cloned in a different document; all other browsers can.
var clone = request.responseXML.firstChild.cloneNode(true); document.getElementsByTagName('body').item(0).appendChild(clone);
cloneNode specification doesn't say whether this
should be allowed; however it does specify for
appendChild that appended nodes must have the same owner
document, and furthermore the
method exists specifically for this purpose. Therefore we infer that
cloning nodes in a different document for use in this document should not
be allowed, and that allowing it is a bug.
Safari 1.3 and 2 will crash when appending a deep clone to this document that was cloned in another document; a shallow clone (or a clone of a node that has no children) is okay.
Overall then — don't use
cloneNode to move
nodes between documents, use
importNode instead, because that's what it's
Opera cannot clone
Notation nodes (it
DOMException (code 9:
Internet Explorer can clone these types of
nodes. (And these are the only browsers in which they're available in the
Safari cannot clone
(Opera throws a
DOMException (code 9:
where Safari creates a
object); Firefox and Internet
Explorer can clone these types of nodes (where they're
available in the first place).