Dom Node Info in XML
DOM Node Info in XML
In the XML DOM, every part of the XML document is represented as a node. Each node has properties that describe its type, name, value, and relationship to other nodes.
Key Node Properties
| Property | Description |
|---|---|
nodeType | Numeric code representing the node type (see below) |
nodeName | Name of the node (e.g., tag name or #text for text nodes) |
nodeValue | Value of the node (text content for text nodes, null for elements) |
parentNode | Reference to the parent node |
childNodes | Collection of child nodes |
firstChild | First child node |
lastChild | Last child node |
previousSibling | Previous sibling node |
nextSibling | Next sibling node |
Common nodeType Values
| Node Type | nodeType Value | Description |
|---|---|---|
ELEMENT_NODE | 1 | An element (e.g., <book>) |
ATTRIBUTE_NODE | 2 | An attribute (e.g., id="101") |
TEXT_NODE | 3 | Text content inside elements |
CDATA_SECTION_NODE | 4 | CDATA section |
COMMENT_NODE | 8 | A comment node |
DOCUMENT_NODE | 9 | The entire document |
Example: Inspect Node Info
const book = xmlDoc.getElementsByTagName("book")[0];// Node typeconsole.log(book.nodeType); // 1 (ELEMENT_NODE)// Node nameconsole.log(book.nodeName); // "book"// Node value (for elements usually null)console.log(book.nodeValue); // null// Access first child (e.g. <title>)const firstChild = book.firstChild;console.log(firstChild.nodeName); // could be "#text" (whitespace) or "title"// To get the first element child ignoring whitespace:const firstElementChild = book.firstElementChild;console.log(firstElementChild.nodeName); // "title"// For a text node inside <title>const titleTextNode = firstElementChild.firstChild;console.log(titleTextNode.nodeType); // 3 (TEXT_NODE)console.log(titleTextNode.nodeValue); // The text content of titleUse Case: Filtering Element Nodes Only
When looping over .childNodes, you often want to skip text or comment nodes:
for(let i = 0; i < book.childNodes.length; i++) { const node = book.childNodes[i]; if(node.nodeType === 1) { // ELEMENT_NODE console.log(node.nodeName); // logs element names only }}Summary
NodeType helps identify what kind of node you’re dealing with.
NodeName gives the name of element or
#textfor text nodes.NodeValue holds text for text nodes,
nullfor elements.Use these to programmatically examine or manipulate XML content.
If you want, I can provide code examples for working with specific node types or handling mixed content!