HTML DOM Element appendChild()
Examples
Append an item to a list:
const node = document.createElement("li");
const textnode = document.createTextNode("Water");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
Before:
- Coffee
- Tea
After:
- Coffee
- Tea
- Water
Move an item from one list to another:
const node = document.getElementById("myList2").lastElementChild;
document.getElementById("myList1").appendChild(node);
Before:
- Coffee
- Tea
- Water
- Milk
After:
- Coffee
- Tea
- Milk
- Water
More examples below.
Definition and Usage
The appendChild()
method appends a node (element) as the last child of an element.
Syntax
element.appendChild(node)
or
node.appendChild(node)
Parameters
Parameter | Description |
node | Required. The node to append. |
Return Value
Type | Description |
Node | The appended node. |
More Examples
To create a paragraph with a text.
- Create a paragraph element
- Create a text node
- Append the text node to the paragraph
- Append the paragraph to the document.
Create a <p> element and append it to a <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 »
Create a <p> element and append it to the document's body:
const para = document.createElement("P");
const node = document.createTextNode("This is a paragraph.");
para.appendChild(node);
document.body.appendChild(para);
Try it Yourself »
Browser Support
element.appendChild()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |