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


Element Object Reference Element Object


Definition and Usage

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

This function returns the replaced node if successful, or NULL if it fails.

Syntax

elementNode.replaceChild(new_node,old_node)

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

Example

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

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 »


Element Object Reference Element Object