XML DOM
replaces the node
The DOM replacement node can be implemented using the replaceChild() method, which replaces the old node with the new node.
The replaceChild() method replaces the specified node.
The nodeValue property replaces the text in the text node.
Try it - instance
The following example uses the XML
file .xml.
The
function loadXMLDoc(),
located in an external JavaScript, is used to load XML files.
Replace the element node
This example uses replaceChild() to replace the first node.
Replace the data in the text node
This example uses the nodeValue property to replace the data in the text node.
Replace the element node
The replaceChild() method is used to replace the node.
The following snippet replaces the first element:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement;
//create a book element, title element and a text node
newNode=xmlDoc.createElement("book");
newTitle=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("A Notebook");
//add the text node to the title node,
newTitle.appendChild(newText);
//add the title node to the book node
newNode.appendChild(newTitle);
y=xmlDoc.getElementsByTagName("book")[0]
//replace the first book node with the new node
x.replaceChild(newNode,y);
Try it out . . .
Example explanation:
-
Use
loadXMLDoc()
to
load .xml
books" into xmlDoc
-
Create a new element node .
-
Create a new element node.
-
Create a new text node with text "A Notebook"
-
Append the new text node to the new element node
-
Append this new element node to the new element node.
-
Replace the first element node with the new one
Replace the data in the text node
The replaceData() method replaces the data in the text node.
The replaceData() method has three parameters:
-
offset - Where to start replacing characters.
The offset value starts at 0.
-
length - How many characters to replace
-
String - The string to insert
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"Easy");
Try it out . . .
Example explanation:
-
Use
loadXMLDoc()
to
load .xml
books" into xmlDoc
-
Gets the text node of the first element node
-
Replace the first 8 characters of the text node with "Easy" using the replaceData method
Use the nodeValue property instead
It is easier to replace the data in the text node with the nodeValue property.
The following snippet replaces the text node value in the first element with "Easy Italian":
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Italian";
Try it out . . .
Example explanation:
-
Use
loadXMLDoc()
to
load .xml
books" into xmlDoc
-
Gets the text
node of the
first element node
-
Use the nodeValue property to change the text of this text node
You
can read more
about changing node values in the chapter Change Nodes.
When node replacement is complete, the original text and tags are replaced with new text and tags.