Document.createTextNode()

Creates a new Text node. This method can be used to escape HTML characters.

Syntax

var text = document.createTextNode(data);
  • text is a Text node.
  • data is a string containing the data to be put in the text node.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<title>createTextNode example</title>
<script>
function addTextNode(text) {
  var newtext = document.createTextNode(text),
      p1 = document.getElementById("p1");

  p1.appendChild(newtext);
}
</script>
</head>

<body>
  <button onclick="addTextNode('YES! ');">YES!</button>
  <button onclick="addTextNode('NO! ');">NO!</button>
  <button onclick="addTextNode('WE CAN! ');">WE CAN!</button>

  <hr />

  <p id="p1">First line of paragraph.</p>
</body>
</html>

Specifications

Specification Status Comment
DOM
The definition of 'Document: createTextNode' in that specification.
Living Standard

Browser compatibility

DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
createTextNodeChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5Opera Full support 7Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0

Legend

Full support
Full support