當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


HTML DOM appendChild()用法及代碼示例

HTML DOM appendChild() 方法用於在子節點列表的末尾創建和添加文本節點。 appendChild() 方法還可用於將元素從當前位置移動到新位置。使用 appendChild(),您可以向列表添加新值,甚至可以在另一個段落下添加新段落。

用法

以下是 appendChild() 方法的語法 -

node.appendChild( 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>

輸出

這將產生以下輸出 -

點擊追加3次後:-

在上麵的例子中 -

我們創建了一個 ID 為 “SampleDIV” 的 div。附加節點將充當此 div 的子節點。

<div id="SampleDIV">
A DIV element
</div>

然後我們有一個名為 “Append” 的按鈕,它將執行函數 AppendP()

<button onclick="AppendP()">Append</button>

AppendP() 函數首先創建一個段落 (p) 元素並將其分配給變量段落。然後使用innerHTML將一些文本添加到段落中,並將變量x附加到文本中。每次單擊“附加”按鈕時,此變量都會增加。最後,我們將新創建的段落附加為 div 元素的子節點 -

var x=1;
function AppendP() {
   var paragraph = document.createElement("P");
   paragraph.innerHTML = "This is paragraph "+x;
   document.getElementById("SampleDIV").appendChild(paragraph);
   x++;
}

相關用法


注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 HTML DOM appendChild() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。