文档:createTextNode() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

创建一个新的 Text 节点。此方法可用于转义 HTML 字符。

语法

js
createTextNode(data)

参数

data

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

返回值

一个 Text 节点。

示例

html
<button>YES!</button>
<button>NO!</button>
<button>WE CAN!</button>

<hr />

<p id="p1">First line of paragraph.</p>
js
function addTextNode(text) {
  const newText = document.createTextNode(text);
  const p1 = document.getElementById("p1");

  p1.appendChild(newText);
}

document.querySelectorAll("button").forEach((button) => {
  button.addEventListener("click", (event) => {
    addTextNode(`${event.target.textContent} `);
  });
});

规范

规范
DOM
# ref-for-dom-document-createtextnode①

浏览器兼容性