Document.createTextNode()

创建一个新的文本节点。这个方法可以用来转义 HTML 字符。

语法

var text = document.createTextNode(data);
  • text 是一个文本节点。
  • data 是一个字符串,包含了要放入文本节点的内容。

示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>createTextNode 示例</title>
</head>

<body>
  <button value="好耶!">好耶!</button>
  <button value="坏耶!">坏耶!</button>
  <button value="Rikka! ">Rikka!</button>
  <button value="日卡卡!">日卡卡!</button>

  <hr />

  <p id="p1">段落的第一行。</p>

  <script>
  const p1 = document.getElementById("p1"),
  buttons = document.body.querySelectorAll(":scope > button");
  function addTextNode(text) {
    p1.appendChild( document.createTextNode(text) );
  }
  buttons.forEach(button =>
    button.addEventListener("click", () =>
      addTextNode(button.value)
    )
  );
  </script>
</body>
</html>

规范

规范 状态 备注
DOM
Document: createTextNode
Living Standard

浏览器兼容性

Update compatibility data on GitHub
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