XML DOM Clone Node
- Previous Page DOM Add Node
- Next Page DOM HttpRequest
Instance
The following example uses an XML file books.xml.
Function loadXMLDoc(), located in external JavaScript, is used to load XML files.
- Copy a node and append it to an existing node
- In this example, cloneNode() is used to copy a node and append it to the root node of the XML document.
Copy a node
The cloneNode() method creates a copy of the specified node.
The cloneNode() method has a parameter (true or false). This parameter indicates whether the copied node includes all attributes and child nodes of the original node.
The following code snippet copies the first <book> node and appends it to the root node of the document:
xmlDoc=loadXMLDoc("books.xml"); oldNode=xmlDoc.getElementsByTagName('book')[0]; newNode=oldNode.cloneNode(true); xmlDoc.documentElement.appendChild(newNode); //Output all titles y=xmlDoc.getElementsByTagName("title"); for (i=0;i<y.length;i++) { document.write(y[i].childNodes[0].nodeValue); document.write("<br />"); }
Output:
Harry Potter Everyday Italian XQuery Kick Start Learning XML Harry Potter
Example Explanation:
- By using loadXMLDoc() Put "books.xml"Load xmlDoc"
- Get the node to be copied
- Copy the node to "newNode" by using the cloneNode method
- Append a new node to the root node of the XML document
- Output all titles in the document
- Previous Page DOM Add Node
- Next Page DOM HttpRequest