HTML DOM Element appendChild() 方法
- Previous page addEventListener()
- Next page attributes
- Go back to the previous level HTML DOM Elements Obheto
定义和用法
appendChild()
方法将节点(元素)作为最后一个子元素添加到元素。
另请参阅:
相关的文档方法:
实例
例子 1
在列表中添加项目:
const node = document.createElement("li"); const textnode = document.createTextNode("Water"); node.appendChild(textnode); document.getElementById("myList").appendChild(node);
添加之前:
- Coffee
- Tea
添加之后:
- Coffee
- Tea
- Water
例子 2
从一个列表向另一个列表中移动列表项:
const node = document.getElementById("myList2").lastElementChild; document.getElementById("myList1").appendChild(node);
Before moving:
- Coffee
- Tea
- Water
- Milk
After moving:
- Coffee
- Tea
- Milk
- Water
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);
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);
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 |
- Previous page addEventListener()
- Next page attributes
- Go back to the previous level HTML DOM Elements Obheto