XML DOM Node Info
Every node can tell you what it is. Three properties carry most of that information: nodeName, nodeValue and nodeType. Their values depend on the kind of node, which is the source of a classic beginner bug.
The three key properties
| Node kind | nodeType |
nodeName |
nodeValue |
|---|---|---|---|
| Element | 1 | the tag name, e.g. book |
null |
| Attribute | 2 | the attribute name, e.g. id |
the attribute value |
| Text | 3 | #text |
the text |
| CDATA section | 4 | #cdata-section |
the text |
| Processing instruction | 7 | the target | the data |
| Comment | 8 | #comment |
the comment text |
| Document | 9 | #document |
null |
nodeName and nodeType are read-only. nodeValue can be set for text, attribute and comment nodes.
The nodeValue trap
An element's nodeValue is always null — its text lives in a child text node. This code is a common mistake:
<!DOCTYPE html>
<html>
<body>
<script>
const xmlDoc = new DOMParser().parseFromString(
'<book id="b1"><title>The Hobbit</title></book>', 'application/xml');
const title = xmlDoc.querySelector('title');
console.log('title.nodeValue =', title.nodeValue); // null!
console.log('title.firstChild.nodeValue =', title.firstChild.nodeValue); // the text
console.log('title.textContent =', title.textContent); // the text, simplest
</script>
</body>
</html>Tip: For elements, use
textContent. It returns the combined text of all descendant text nodes and works even when the element is empty ("") — whereasfirstChild.nodeValuecrashes when there is no first child.
Inspecting different node kinds
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<book id="b1"><!-- classic --><title>The Hobbit</title><?index level="2"?></book>`;
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
const book = xmlDoc.documentElement;
const nodes = [xmlDoc, book, book.getAttributeNode('id'), ...book.childNodes, book.querySelector('title').firstChild];
for (const n of nodes) {
console.log(String(n.nodeType).padEnd(3), String(n.nodeName).padEnd(10), JSON.stringify(n.nodeValue));
}
</script>
</body>
</html>More information about a node
| Property | Gives you |
|---|---|
tagName |
Element name (elements only; same as nodeName) |
localName, prefix, namespaceURI |
Parts of a namespaced name |
attributes |
A NamedNodeMap of the element's attributes |
hasAttribute(name) / hasAttributes() |
Whether an attribute exists / any exist |
hasChildNodes() |
Whether there are any children |
childElementCount |
Number of child elements |
ownerDocument |
The document the node belongs to |
isConnected |
Whether it is currently in the document |
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<lib:library xmlns:lib="urn:example:library">
<lib:book id="b1" genre="fantasy" format="paper"><lib:title>The Hobbit</lib:title></lib:book>
</lib:library>`;
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
const book = xmlDoc.documentElement.firstElementChild;
console.log('tagName :', book.tagName);
console.log('localName :', book.localName);
console.log('prefix :', book.prefix);
console.log('namespaceURI :', book.namespaceURI);
console.log('attributes :', [...book.attributes].map(a => `${a.name}=${a.value}`).join(', '));
console.log('has genre? :', book.hasAttribute('genre'));
console.log('child elements:', book.childElementCount);
</script>
</body>
</html>Testing the node type
When walking the tree you often need to treat elements and text differently. Compare nodeType with the named constants for readable code:
for (const child of book.childNodes) {
if (child.nodeType === Node.ELEMENT_NODE) {
console.log('element:', child.nodeName);
} else if (child.nodeType === Node.TEXT_NODE && child.nodeValue.trim() !== '') {
console.log('text:', child.nodeValue.trim());
}
}Skipping whitespace-only text nodes with .trim() !== '' is a pattern you'll use again and again.
Test yourself
What is the nodeValue of an element node?
- Its text
- Its tag name
null- Its first attribute
What is the nodeName of a text node?
text#text- The parent's name
null
Which is the safest way to read the text inside <title>?
title.nodeValuetitle.firstChild.nodeValuetitle.textContenttitle.value