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);

添加之前:

  • 커피

添加之后:

  • 커피

직접 시험해 보세요

例子 2

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

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

이동 전:

  • 커피

  • 우유

이동 후:

  • 커피
  • 우유

직접 시험해 보세요

예제 3

텍스트가 포함된 구절 생성

  • 구절 요소 생성
  • 텍스트 노드 생성
  • 구절에 텍스트 노드 추가
  • 문서에 구절 추가

<div> 요소에 <p> 요소를 생성하고 추가하십시오:

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

직접 시험해 보세요

예제 4

문서 본문에 <p> 요소를 생성하고 추가하십시오:

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

직접 시험해 보세요

문법

element.appendChild(node)

또는

node.appendChild(node)

파라미터

파라미터 설명
node 필수. 추가할 노드.

반환 값

타입 설명
노드 추가된 노드.

브라우저 지원

element.appendChild() DOM Level 1 (1998) 기능입니다.

모든 브라우저에서 완전히 지원됩니다:

크롬 IE 에지 파이어폭스 사파리 오페라
크롬 IE 에지 파이어폭스 사파리 오페라
지원 9-11 지원 지원 지원 지원