Object Attr CDATASection
CharacterData Comment Document DocumentFragment
DocumentType Entity EntityReference Node
Notation ProcessingInstruction Text
Object.cloneNode(deep)
The cloneNode method creates a clone node which is an exact replica of this node,
except that it cannot have a parent node. The one parameter, deep, is a boolean
which determines whether the node's children are also cloned. If it is false, then
only the node itself (and any attributes if it is an element) is cloned; otherwise the
cloning is recursive and includes all children. Note that if the parameter is set to
false, any text that the node may have will not be cloned, as this constitutes a
child node.
The following example demonstrates this method. Using the 'library.xml' file,
the code recursively creates a clone of the first child node of the document root (the
first 'book') and appends it to the root's children. It then creates a list of all the
'title' nodes and iterates through them displaying the value of each
firstChild node (the text).
XML:
<library>
<book>
<category>fiction</category>
<title>Eyeless in Gaza</title>
<author>Aldous Huxley</author>
</book>
<book>
<category>classics</category>
<title>John Barleycorn</title>
<author>Jack London</author>
</book>
</library>
Code (JavaScript):
var xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.load("library.xml");
var root = xml_doc.documentElement;
var curr_node = root.firstChild;
var new_node = curr_node.cloneNode(true);
root.appendChild(new_node);
var name_list = root.getElementsByTagName("title");
var i, n_names = name_list.length;
for (i = 0; i < n_names; i++)
document.write(name_list[i].firstChild.nodeValue + "<br>");
Output:
Eyeless in Gaza
John Barleycorn
Eyeless in Gaza
|