Latest web development tutorials

XML DOM - Replacement Node

replaceChild () method replaces the specified node.

nodeValue property replaces text node text.


Examples

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

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"

Examples explain:

  1. Use loadXMLDoc () to " the Books.xml " into xmlDoc
  2. Creates a new element node <book>
  3. Creates a new element node <title>
  4. Create a new text node with the text "A Notebook"
  5. To a new element node <title> add this new text node
  6. To a new element node <book> add this new element node <title>
  7. 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

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];

x.replaceData(0,8,"Easy");

try it"

Examples explain:

  1. Use loadXMLDoc () to " the Books.xml " into xmlDoc
  2. Gets the first text node <title> element node
  3. 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

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];

x.nodeValue="Easy Italian";

try it"

Examples explain:

  1. Use loadXMLDoc () to " the Books.xml " into xmlDoc
  2. Gets the first text node <title> element node
  3. Use the nodeValue property to change the text node

You can change the node Read more about changing node values described in this chapter.