HTML DOM appendChild() 方法
htmlweb developmentfront end technology更新于 2024/6/11 14:04:17
HTML DOM appendChild() 方法用于在子节点列表末尾创建并添加一个文本节点。appendChild() 方法也可用于将元素从当前位置移动到新位置。使用 appendChild(),您可以向列表添加新值,甚至可以在另一个段落下添加新段落。
语法
以下是 appendChild() 方法的语法 −
node.appendChild( node )
此处,参数 node 是要附加的对象。它是一个必需的参数值。
示例
让我们看一个 appendChild() 方法的示例 −
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a paragraph and append it to the div</p>
<div id="SampleDIV">
A DIV element
</div>
<button onclick="AppendP()">Append</button>
<script>
var x=1;
function AppendP() {
var paragraph = document.createElement("P");
paragraph.innerHTML = "This is paragraph "+x;
document.getElementById("SampleDIV").appendChild(paragraph);
x++;
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击三次"附加"后:−

在上面的例子中,−
我们创建了一个 id 为"SampleDIV"的 div。附加的节点将作为此 div 的子节点。
<div id="SampleDIV> 一个 DIV 元素 </div>
然后我们有一个名为"附加"的按钮这将执行 AppendP() 函数
<button onclick="AppendP()>>Append</button>
AppendP() 函数首先创建一个段落 (p) 元素并将其赋值给变量 param。然后使用 innerHTML 向段落添加一些文本,并将变量 x 附加到文本中。每次点击"Append"按钮时,此变量都会递增。最后,我们将新创建的段落作为 div 元素的子节点附加到元素中 −
var x=1;
function AppendP() {
var paragraph = document.createElement("P");
paragraph.innerHTML = "This is paragraph "+x;
document.getElementById("SampleDIV").appendChild(paragraph);
x++;
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

