Dom Navigating in XML
DOM Navigating in XML
DOM navigation means moving through the nodes (elements, text, attributes) of an XML document tree using properties like parent, child, sibling, etc.
Key DOM Navigation Properties
| Property | Description |
|---|---|
parentNode | Gets the parent node of the current node |
childNodes | Returns a collection (NodeList) of all child nodes (including text nodes) |
firstChild | Gets the first child node |
lastChild | Gets the last child node |
nextSibling | Gets the next sibling node |
previousSibling | Gets the previous sibling node |
children | Returns only element child nodes (ignores text nodes) |
Example XML
<library> <book id="101"> <title>Effective Java</title> <author>Joshua Bloch</author> </book> <book id="102"> <title>Clean Code</title> <author>Robert C. Martin</author> </book></library>Navigating Nodes Using JavaScript DOM
// Assume xmlDoc is parsed XML document// Get <library> root elementconst library = xmlDoc.getElementsByTagName("library")[0];// Access first child <book>const firstBook = library.firstElementChild; // or library.children[0]// Get the next sibling of the first <book>const secondBook = firstBook.nextElementSibling;// Access the <title> of second bookconst title = secondBook.getElementsByTagName("title")[0].textContent;console.log(title); // Outputs: Clean Code// Navigate to parent of <title>const titleNode = secondBook.getElementsByTagName("title")[0];const parent = titleNode.parentNode; // <book> elementImportant Notes
.childNodesincludes all child nodes (elements, text nodes like whitespace, comments)..childrenincludes only element nodes (usually what you want for element traversal).Use
.firstElementChildand.nextElementSiblingto skip non-element nodes like text/whitespace.
Full Example: Traversing XML DOM Tree
const library = xmlDoc.documentElement; // <library>console.log("Library contains books:");for(let i = 0; i < library.children.length; i++) { const book = library.children[i]; const id = book.getAttribute("id"); const title = book.getElementsByTagName("title")[0].textContent; const author = book.getElementsByTagName("author")[0].textContent; console.log(`Book ${id}: "${title}" by ${author}`);}Summary
| Navigation Type | Property |
|---|---|
| Parent node | parentNode |
| Child nodes (all) | childNodes |
| Child elements only | children |
| First child node | firstChild |
| First child element | firstElementChild |
| Next sibling node | nextSibling |
| Next sibling element | nextElementSibling |
| Previous sibling node | previousSibling |
| Previous sibling elem | previousElementSibling |
Want a practical example with code you can run?