HTML DOM 元素 appendChild()
示例
向列表中追加一个项目
const node = document.createElement("li");
const textnode = document.createTextNode("Water");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
之前
- 咖啡
- 茶
之后
- 咖啡
- 茶
- Water
将一个项目从一个列表移动到另一个列表
const node = document.getElementById("myList2").lastElementChild;
document.getElementById("myList1").appendChild(node);
之前
- 咖啡
- 茶
- Water
- 牛奶
之后
- 咖啡
- 茶
- 牛奶
- Water
更多示例见下文。
描述
appendChild()
方法将一个节点(元素)作为最后一个子节点追加到元素中。
另请参阅
相关文档方法
语法
元素.appendChild(节点)
或
节点.appendChild(节点)
参数
参数 | 描述 |
node | 必需。 要追加的节点。 |
返回值
类型 | 描述 |
节点 | 追加的节点。 |
更多示例
创建一个带文本的段落。
- 创建段落元素
- 创建文本节点
- 将文本节点追加到段落中
- 将段落追加到文档中。
创建一个 <p> 元素并将其追加到 <div> 元素中
const para = document.createElement("p");
const node = document.createTextNode("这是一个段落。");
para.appendChild(node);
document.getElementById("myDIV").appendChild(para);
自己动手试一试 »
创建一个 <p> 元素并将其追加到文档的 body 中
const para = document.createElement("P");
const node = document.createTextNode("这是一个段落。");
para.appendChild(node);
document.body.appendChild(para);
自己动手试一试 »
浏览器支持
element.appendChild()
是 DOM Level 1 (1998) 的特性。
所有浏览器都完全支持。
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 9-11 |