此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

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 ⁨2015年7月⁩.

创建新的文本节点。该方法可用于转义 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①

浏览器兼容性