XML DOM previousSibling Property
Element Object
Definition and Usage
The previousSibling property returns the previous sibling node of the selected element (the next node at the same tree level).
If no such node exists, this property returns NULL.
Syntax
elementNode.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 previous node and then continues to check 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
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 a node
Element Object