XML DOM previousSibling Property | Tutorial
Tutorial -- Learning not just technology, but dreams!
- Home
- HTML
- JavaScript
- CSS
- Vue
- React
- Python3
- Java
- C
- C++
- C#
- AI
- Go
- SQL
- Linux
- VS Code
- Bootstrap
- Git
- Local Bookmarks
XML DOM Tutorial
XML DOM Tutorial DOM Introduction DOM Nodes DOM Node Tree DOM Parser DOM Load Function DOM Methods DOM Accessing Nodes DOM Node Information DOM NodeList and NamedNodeMap DOM Traversing the Node Tree DOM Browser Differences DOM Navigating Nodes DOM Getting Node Values DOM Changing Node Values DOM Removing Nodes DOM Replacing Nodes DOM Creating Nodes DOM Adding Nodes DOM Cloning Nodes DOM XMLHttpRequest DOM Node Types DOM Node DOM NodeList DOM NamedNodeMap DOM Document DOM DocumentImpl DOM DocumentType DOM ProcessingInst DOM Element DOM Attribute DOM Text DOM CDATA DOM Comment DOM XMLHttpRequest DOM ParseError Obj DOM Parser Errors DOM Summary DOM Examples DOM Validation
XML DOM β ProcessingInstruction Object
Explore Further
- Computer Science
- Scripting Languages
- Web Browsers
- Software
- Web Service
- Programming
- Development Tools
- Web Services
- Programming Languages
- Web Design and Development
XML DOM previousSibling Property
Definition and Usage
The previousSibling property returns the previous sibling node (the next node in the same tree level) of the selected element.
If no such node exists, the property returns NULL.
Syntax
elementNode.previousSibling
Tips and Notes
Note: Firefox and most other browsers will treat empty whitespace or line breaks between nodes as text nodes, while Internet Explorer will ignore whitespace text nodes between nodes. Therefore, in the example below, we will use a function to check the node type of the previous sibling.
The node type of an element node is 1, so if the previous sibling is not an element node, it will move to the previous node and then continue to check if this node is an element node. This process continues until the previous sibling element node is found. Using this method, we can get the correct result in all browsers.
Tip: To learn more about browser differences, visit our DOM Browsers chapter in our XML DOM Tutorial.
Example
The following code snippet uses loadXMLDoc() to load "books.xml" into xmlDoc and gets the previous sibling node from the first <author> 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");
document.write(x.nodeName);
document.write(" = ");
document.write(x.childNodes.nodeValue);
y=get_previoussibling(x);
document.write("<br>Previous sibling: ");
document.write(y.nodeName);
document.write(" = ");
document.write(y.childNodes.nodeValue);
The code above will output:
author = Giada De Laurentiis
Previous sibling: title = Everyday Italian
Try it Yourself
nextSibling - Get the next sibling node of a node
YouTip