创建一个新的文本
节点。这个方法可以用来转义 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 |
浏览器兼容性
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.