XML DOM - Replacement Node
replaceChild () method replaces the specified node.
nodeValue property replaces text node text.
Try - Example
The following example uses XML files the Books.xml .
Function loadXMLDoc () , in an external JavaScript is used to load the XML file.
Replace element node
This example uses replaceChild () to replace the first <book> node.
Data replacement text node
This example uses the nodeValue property to replace the data in a text node.
Replace element node
replaceChild () method is used to replace the node.
The following code fragment replaces the first <book> element:
Examples
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"
Examples explain:
- Use loadXMLDoc () to " the Books.xml " into xmlDoc
- Creates a new element node <book>
- Creates a new element node <title>
- Create a new text node with the text "A Notebook"
- To a new element node <title> add this new text node
- To a new element node <book> add this new element node <title>
- To replace the first <book> element node for the new <book> element node
Data replacement text node
replaceData () method is used to replace the data in a text node.
replaceData () method takes three arguments:
- offset - Where to begin replacing characters. offset value begins with 0.
- length - the number of characters to be replaced
- string - the string to insert
Examples
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"Easy");
try it"
Examples explain:
- Use loadXMLDoc () to " the Books.xml " into xmlDoc
- Gets the first text node <title> element node
- ReplaceData method using the first eight characters of the text node is replaced by "Easy"
Instead of using the nodeValue property
With nodeValue property to replace the data in a text node will be easier.
The following code fragment will replace the first <title> element node values in the text with "Easy Italian":
Examples
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Italian";
try it"
Examples explain:
- Use loadXMLDoc () to " the Books.xml " into xmlDoc
- Gets the first text node <title> element node
- Use the nodeValue property to change the text node
You can change the node Read more about changing node values described in this chapter.