XML DOM Replacing Nodes
- Previous Page DOM Delete Node
- Next Page DOM Create Node
replaceChild()
The method replaces the specified node.
nodeValue
Properties replace the text in the text node.
Replace element nodes
replaceChild()
The method is used to replace nodes.
The following code snippet replaces the first <book> element:
Example
xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.documentElement; // Create a book element, title element, and text node newNode=xmlDoc.createElement("book"); newTitle=xmlDoc.createElement("title"); newText=xmlDoc.createTextNode("A New Book"); // Add the text node to the title node newTitle.appendChild(newText); // Add this 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 yourself
- The example explains: books.xml loaded to
xmlDoc
in - Create a new element node <book>
- Create a new element node <title>
- Create a new text node containing the text "A New Book"
- Append this new text node to the new element node <title>
- Append this new element node <title> to the new element node <book>
- Replace the first <book> element node with a new <book> element node
Replace the data in the text node
replaceData()
The method is used to replace the data in the text node.
replaceData()
The method has three parameters:
- offset - Where to start replacing characters. The offset starts from zero
- length - The number of characters to replace
- string - The string to be inserted
Example
xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0].childNodes[0]; x.replaceData(0,4,"A New Book");
Try it yourself
- The example explains: books.xml loaded to
xmlDoc
in - Get the text node of the first <title> element node
- Use
replaceData()
The method replaces the first eight characters of the text node with "A New Book"
Use the nodeValue property instead
Use nodeValue
Properties are easier to replace the data in the text node.
The following code snippet replaces the text node value of the first <title> element with "A New Book":
Example
xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0].childNodes[0]; x.nodeValue="一本新书";
Try it yourself
- The example explains: books.xml loaded to
xmlDoc
in - Get the text node of the first <title> element node
- Use
nodeValue
Use attributes to change the text of a text node
You can read more about changing node values in the 'Change Node' chapter.
- Previous Page DOM Delete Node
- Next Page DOM Create Node