JS DOM: Node value

By Xah Lee. Date: . Last updated: .

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

When to prefer other APIs

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.