HTML DOM Element appendChild() method
- Previous Page addEventListener()
- Next Page attributes
- Go to the Previous Level HTML DOM Elements Object
Definition and usage
appendChild()
The method adds a node (element) as the last child element to the element.
See also:
Related document methods:
Instance
Example 1
Add items to a list:
const node = document.createElement("li"); const textnode = document.createTextNode("Water"); node.appendChild(textnode); document.getElementById("myList").appendChild(node);
Before adding:
- Coffee
- Tea
After adding:
- Coffee
- Tea
- Water
Example 2
Move list items from one list to another:
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 a paragraph element
- Create a text node
- Append a text node to the paragraph
- Append a paragraph to the 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 | The appended 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 to the Previous Level HTML DOM Elements Object