Document:createTextNode() 方法

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

创建新的文本节点。该方法可用于转义 HTML 字符。

语法

js
createTextNode(data)

参数

data

包含要放入文本节点的数据的字符串。

返回值

文本节点。

示例

html
<!doctype html>
<html lang="zh-CN">
  <head>
    <title>createTextNode 示例</title>
    <script>
      function addTextNode(text) {
        const newtext = document.createTextNode(text);
        const p1 = document.getElementById("p1");

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

  <body>
    <button onclick="addTextNode('是!');">是!</button>
    <button onclick="addTextNode('否!');">否!</button>
    <button onclick="addTextNode('我们可以!');">我们可以!</button>

    <hr />

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

规范

Specification
DOM
# ref-for-dom-document-createtextnode①

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
createTextNode

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support