JS DOM: Node value
Method nodevalue
node.nodeValue-
- Return the content of text node, as string. (text node is a node type value of Node Type value 3.)
- For most other node types, it return null.
As of 2012-04-29, this works in all major browsers.
// create a paragraph element and insert it as first node of body const xnew = document.createElement("p"); xnew.setAttribute("id", "w5ZPn"); xnew.textContent = "good noon"; document.body.prepend(xnew); // paragraph element const xx = document.getElementById("w5ZPn"); // nodeValue is null console.log(xx.nodeValue === null); // get its first child. nodeValue is the text content console.log(xx.firstChild.nodeValue === "good noon");
To change text node, you can set nodeValue to some text,
but it must be a text node.
🟢 tip: when to use nodevalue
nodeValue is most useful if you are working in XML, or you need to work on Whitespace Nodes.
If you are working with HTML for websites, it's more practical and convenient to use textContent or innerHTML
property.
in js when is node.nodeValue useful
in js when is node.nodeValue useful
(ai answer)
node.nodeValue is useful when you already have a reference to a Text, Comment, CDATA, or Attr node (not an Element).
What it returns
| Node type | nodeValue |
|---|---|
| Text | The text content |
| Comment | The comment text |
| CDATASection | The CDATA content |
| Attr | The attribute value |
| ProcessingInstruction | Content (excluding target) |
| Element, Document, etc. | null (setting does nothing) |
Practical cases
- You hold a text node and want to read/write only that node’s data:
const textNode = document.createTextNode("hello"); textNode.nodeValue; // "hello" textNode.nodeValue = "hi"; // updates just this node - Direct text child of an element (common pattern):
This mutates the existing text node instead of replacing all children (unlike settingelement.firstChild.nodeValue = "new text"; textContent). - Walking the DOM (siblings, tree walkers, mutation handling) where you need the raw value of text or comment nodes.
- Comments or CDATA when you need to inspect or modify them.
- Attr nodes (rare nowadays) — if you obtained one via
getAttributeNode().
When to prefer other APIs
- For normal element text, use
textContent(orinnerText). It’s simpler and handles descendants. - Prefer
getAttribute/setAttribute(or element properties) over Attr nodes.
Summary: Reach for nodeValue when you’re working with a specific Text/Comment/Attr node you already have. For everything else starting from an Element, textContent is usually the better choice.