XML DOM Replacing Nodes
The replaceChild() method replaces the specified node.
The nodeValue property replaces the text in a text node.
Try it - Example
The following example uses the XML file books.xml.
function loadXMLDoc(), located in an external JavaScript, used to load the XML file.
Replace an Element Node
This example uses replaceChild() to replace the first
Replace Data in a Text Node
This example uses the nodeValue property to replace the data in a text node.
Replace an Element Node
The replaceChild() method is used to replace nodes.
The following code snippet replaces the first
Example
xmlDoc
=
loadXMLDoc
(
"
books.xml
"
)
;
x
=
xmlDoc
.
documentElement
;
//
Create a new book element, title element and node 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 »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Create a new element node
- Create a new element node
- Create a new text node with the text "A Notebook"
- To the new element node
append this new text node - To the new element node
Append this new element node - Replace the first
replace the element node with the new element nodes
Replace Data in a Text Node
The replaceData() method is used to replace data in a 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
Example
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"Easy");
Try it »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Get the first
element node's text node - Use the replaceData method to replace the first 8 characters of the text node with "Easy"
Use the nodeValue property instead
It is easier to replace data in a text node using the nodeValue property.
The following code snippet will replace the first with "Easy Italian"
Example
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Italian";
Try it »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Get the first
element node's text node - Use the nodeValue property to change this text node's text
You can addChanging NodesRead more about changing node values in this chapter.