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

XML DOM replaceChild() Method

XML DOM replaceChild() Method


Node Object Reference Node object


Definition and Usage

The replaceChild() method replaces one child node with another.

If successful the function returns the replaced node, if it fails then NULL.

Syntax

elementNode.replaceChild(new_node,old_node)

Parameters Description
new_node Required. Specifies the new node.
old_node Required. Specifies the child node to be replaced.

Example

The following code snippet uses loadXMLDoc() to load "books.xml" load into xmlDoc, and replace the first nodes in the document:

Example

xmlDoc

=

loadXMLDoc

(

"

books.xml

"

)

;

x

=

xmlDoc

.

documentElement

;

//

Create book element, title element and text node

newNode

=

xmlDoc

.

createElement

(

"

book

"

)

;

newTitle

=

xmlDoc

.

createElement

(

"

title

"

)

;

newText

=

xmlDoc

.

createTextNode

(

"

A Notebook

"

)

;

//

Add text node to title node

newTitle

.

appendChild

(

newText

)

;

//

Add title node to book node

newNode

.

appendChild

(

newTitle

)

;

y

=

xmlDoc

.

getElementsByTagName

(

"

book

"

)

[

0

]

//

Replace the first book node with the new node

x

.

replaceChild

(

newNode

,

y

)

;

z

=

xmlDoc

.

getElementsByTagName

(

"

title

"

)

;

for

(

i

=

0

;

i

<

z

.

length

;

i

++

)

{

document

.

write

(

z

[

i

]

.

childNodes

[

0

]

.

nodeValue

)

;

document

.

write

(

"


"

)

;

}

Try it »


Node Object Reference Node object