Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท DOM: Document and Elements

document.createTextNode()

Reference for createTextNode(): create a Text node that always shows its data as plain text, never as HTML. See when to use it instead of textContent.

document.createTextNode() creates a Text node holding the string you pass. A text node is a leaf of the DOM tree: it has no children and no tag. Whatever the string contains, including < and &, the browser displays literally, so the node can never inject markup.

Often you do not need it, because textContent and append("text") do the job. It is useful when you want a text node as a separate object, for example to update only that piece of text later, or to mix text and elements in a precise order.

JavaScript
const text = document.createTextNode("Hello <world>");
paragraph.append(text);

Try it

Text is never parsed as HTML
Update one text node in place

Syntax

JavaScript
document.createTextNode(data)
Name Description
data The text content of the node. Other values are converted to a string.

Return value: a new Text node that is not yet in any document tree.

Exceptions: none for normal values.

Usage notes

  • Safe for untrusted text. Like textContent, the data is shown literally. Prefer these over innerHTML for user-provided strings.
  • Read and write with .data. text.data (or nodeValue) gets or replaces the string. text.length gives its length, and text.splitText(offset) splits it in two.
  • Adjacent text nodes stay separate. Appending two text nodes does not merge them; element.normalize() does. This matters when you count childNodes.
  • Same effect as strings in append(). parent.append("hi") creates a text node for you. Use createTextNode() when you want to keep a handle on it.
  • Whitespace counts. Whitespace between tags in HTML source becomes text nodes too, which is why childNodes shows more than children.
  • Setting textContent replaces all children. el.textContent = "x" removes every child and inserts one text node. It is simpler when the element should contain only text.
  • Comments and fragments. createComment() and createDocumentFragment() are the siblings of this method for other node kinds.

Browser support

Supported in every browser.