HTML DOM Element appendChild() 方法

定义和用法

appendChild() 方法将节点(元素)作为最后一个子元素添加到元素。

另请参阅:

insertBefore() 方法

replaceChild() 方法

removeChild() 方法

remove() 方法

childNodes 属性

firstChild 属性

lastChild 属性

firstElementChild 属性

lastElementChild 属性

相关的文档方法:

createElement() 方法

createTextNode() 方法

实例

例子 1

在列表中添加项目:

const node = document.createElement("li");
const textnode = document.createTextNode("Water");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);

添加之前:

  • Coffee
  • Tea

添加之后:

  • Coffee
  • Tea
  • Water

Try it yourself

例子 2

从一个列表向另一个列表中移动列表项:

const node = document.getElementById("myList2").lastElementChild;
document.getElementById("myList1").appendChild(node);

Before moving:

  • Coffee
  • Tea

  • Water
  • Milk

After moving:

  • Coffee
  • Tea
  • Milk

  • Water

Try it yourself

Example 3

Create a paragraph with text:

  • Create paragraph element
  • Create text node
  • Append text node to paragraph
  • Append paragraph to document

Create a <p> element and append it to the <div> element:

const para = document.createElement("p");
const node = document.createTextNode("This is a paragraph.");
para.appendChild(node);
document.getElementById("myDIV").appendChild(para);

Try it yourself

Example 4

Create a <p> element and append it to the body of the document:

const para = document.createElement("P");
const node = document.createTextNode("This is a paragraph.");
para.appendChild(node);
document.body.appendChild(para);

Try it yourself

Syntax

element.appendChild(node)

or

node.appendChild(node)

Parameter

Parameter Description
node Required. The node to be appended.

Return value

Type Description
Node Added node.

Browser support

element.appendChild() It is a DOM Level 1 (1998) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support