HTML DOM createTextNode() 方法
htmlweb developmentfront end technology更新于 2025/9/24 3:56:17
HTML DOM createTextNode() 方法用于创建具有指定文本的文本节点。
示例
我们来看一个 createTextNode() 方法的示例 −
<!DOCTYPE html>
<html>
<body>
<h2>createTextNode() example</h2>
<p>Click the below button to create a p element with some text.</p>
<button onclick="createText()">CREATE</button>
<script>
function createText() {
var x = document.createElement("P");
var p = document.createTextNode("This is a sample paragraph created with
createTextNode()");
x.appendChild(p);
document.body.appendChild(x);
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击"创建"按钮 −

在上面的例子中 −
我们创建了一个"创建"按钮,当用户点击该按钮时,它将执行 createText() 函数 −
<button onclick="createText()>CREATE</button>
createText() 方法创建 <p>使用 document 对象的 createElement() 方法创建一个 <p> 元素,并将其赋值给变量 x。然后,我们使用 createTextNode() 创建一个包含文本的文本节点,并将其赋值给变量 p。
接下来,我们使用 appendChild() 方法将文本节点附加到 <p> 元素。最后,使用 document.body appendChild() 方法将 <p> 元素和文本节点一起附加到 document 中:
function createText() {
var x = document.createElement("P");
var p = document.createTextNode("This is a sample paragraph created with createTextNode()");
x.appendChild(p);
document.body.appendChild(x);
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

