Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

XML DOM – Replacing Nodes

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 node.

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 element:

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:

  1. Use loadXMLDoc() to load "books.xml" load into xmlDoc
  2. Create a new element node
  3. Create a new element node </li> <li>Create a new text node with the text "A Notebook"</li>
  4. To the new element node append this new text node</li>
  5. To the new element node Append this new element node </li>
  6. 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:

Example

xmlDoc=loadXMLDoc("books.xml");

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

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

Try it »

Example explanation:

  1. Use loadXMLDoc() to load "books.xml" load into xmlDoc
  2. Get the first element node's text node</li>
  3. 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" element's text node value:</p>

Example

xmlDoc=loadXMLDoc("books.xml");

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

x.nodeValue="Easy Italian";

Try it »

Example explanation:

  1. Use loadXMLDoc() to load "books.xml" load into xmlDoc
  2. Get the first element node's text node</li>
  3. Use the nodeValue property to change this text node's text

You can addChanging NodesRead more about changing node values in this chapter.