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

XML DOM previousSibling Property

XML DOM previousSibling Property


Node Object Reference Node object


Definition and Usage

The previousSibling property returns the node immediately preceding an element (in the same tree level).

If there is no such node, this property returns null.

Syntax

nodeObject.previousSibling


Tips and Notes

**Note:** Firefox and most other browsers treat the empty spaces or line breaks generated between nodes as text nodes, while Internet Explorer ignores the whitespace text nodes generated between nodes. Therefore, in the example below, we use a function to check the node type of the previous sibling node.

The node type of an element node is 1, so if the previous sibling node is not an element node, it moves to the next node and continues checking whether that node is an element node. This process continues until the previous sibling element node is found. In this way, we can get the correct result in all browsers.

**Tip:** For more about browser differences, see our section in the XML DOM tutorial DOM Browsers section.


Example

The following code snippet uses loadXMLDoc() to load "books.xml" Load into xmlDoc, and from the first get the previous sibling node of an element:

Example

//

Get the previous sibling node of an element node

function

get_previoussibling

(

n

)

{

x

=

n

.

previousSibling

;

while

(

x

.

nodeType

!=

1

)

{

x

=

x

.

previousSibling

;

}

return

x

;

}

xmlDoc

=

loadXMLDoc

(

"

books.xml

"

)

;

x

=

xmlDoc

.

getElementsByTagName

(

"

author

"

)

[

0

]

;

document

.

write

(

x

.

nodeName

)

;

document

.

write

(

"

=

"

)

;

document

.

write

(

x

.

childNodes

[

0

]

.

nodeValue

)

;

y

=

get_previoussibling

(

x

)

;

document

.

write

(

"


Previous sibling:

"

)

;

document

.

write

(

y

.

nodeName

)

;

document

.

write

(

"

=

"

)

;

document

.

write

(

y

.

childNodes

[

0

]

.

nodeValue

)

;

The code above will output:

author = Giada De Laurentiis

Previous sibling: title = Everyday Italian

Try it »


Try it

nextSibling - Get the next sibling node of an element node


Node Object Reference Node object