XML DOM - Replacing Nodes
The replaceChild()
method replaces a specified node.
The nodeValue
property replaces the text in a text node.
Try It Yourself - Examples
The following examples use the XML file books.xml. The loadXMLDoc()
function, located in an external JavaScript, is used to load the XML file.
Replace an Element Node
The replaceChild()
method is used to replace a node.
The following code snippet replaces the first <book>
element:
Example
xmlDoc = loadXMLDoc("books.xml");
x = xmlDoc.documentElement;
// Create new book element, title element, and text node
newNode = xmlDoc.createElement("book");
newTitle = xmlDoc.createElement("title");
newText = xmlDoc.createTextNode("A Notebook");
// Append the text node to the title element
newTitle.appendChild(newText);
// Append the title element to the book element
newNode.appendChild(newTitle);
y = xmlDoc.getElementsByTagName("book")[0];
// Replace the first book element with the new book element
x.replaceChild(newNode, y);
Example Explanation:
- Use
loadXMLDoc()
to load "books.xml" intoxmlDoc
- Create a new
<book>
element node - Create a new
<title>
element node - Create a new text node with the text "A Notebook"
- Append the new text node to the new
<title>
element - Append the new
<title>
element to the new<book>
element - Replace the first
<book>
element node with the new<book>
element node
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
Example Explanation:
- Use
loadXMLDoc()
to load "books.xml" intoxmlDoc
- Get the text node of the first
<title>
element node - Use the
replaceData
method to replace the first 8 characters of the text node with "Easy"
Using the nodeValue Property Instead
Using the nodeValue
property to replace data in a text node is easier.
The following code snippet replaces the text node value in the first <title>
element with "Easy Italian":
Example
Example Explanation:
- Use
loadXMLDoc()
to load "books.xml" intoxmlDoc
- Get the text node of the first
<title>
element node - Use the
nodeValue
property to change the text of the text node
You can read more about changing node values in the Changing Nodes chapter.