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.
const text = document.createTextNode("Hello <world>"); paragraph.append(text);
Try it
Syntax
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 overinnerHTMLfor user-provided strings. - Read and write with
.data.text.data(ornodeValue) gets or replaces the string.text.lengthgives its length, andtext.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 countchildNodes. - Same effect as strings in
append().parent.append("hi")creates a text node for you. UsecreateTextNode()when you want to keep a handle on it. - Whitespace counts. Whitespace between tags in HTML source becomes text nodes too, which is why
childNodesshows more thanchildren. - Setting
textContentreplaces 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()andcreateDocumentFragment()are the siblings of this method for other node kinds.
Browser support
Supported in every browser.