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 YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown