HTML DOM appendChild() Method
HTML DOM Methods
HTML DOM appendChild() Method
CompletedHTML DOM appendChild() Method
HTML DOM appendChild() Method
CompletedExample
Append an item in a list:
var node = document.createElement("LI"); // Create a <li>
node
var textnode = document.createTextNode("Water"); // Create a text node
node.appendChild(textnode); // Append the text to <li>
document.getElementById("myList").appendChild(node); // Append <li> to
<ul> with id="myList"
Before appending:
- Coffee
- Tea
After appending:
- Coffee
- Tea
- Water
Try it Yourself
More "Try it Yourself" examples below.
Definition and Usage
CompletedThe appendChild() method appends a node as the last child of a node.
Tip: If you want create a new paragraph, with text, remember to create the text as a Text node which you append to the paragraph, then append the paragraph to the document.
You can also use this method to move an element from one element to another (See "More Examples").
Tip: Use the insertBefore() method to insert a new child node before a specified, existing, child node.
Browser Support
CompletedThe numbers in the table specify the first browser version that fully supports the method.
| Method | |||||
|---|---|---|---|---|---|
| appendChild() | Yes | Yes | Yes | Yes | Yes |
Syntax
Completed
node.appendChild(node)Parameter Values
Completed| Parameter | Type | Description |
|---|---|---|
| node | Node object | Required. The node object you want to append |
Technical Details
Completed| Return Value: | A Node Object, representing the appended node |
|---|---|
| DOM Version | Core Level 1 Node Object |
More Examples
CompletedExample
Move a list item from one list to another:
var node = document.getElementById("myList2").lastChild;
document.getElementById("myList1").appendChild(node);
Before appending:
- Coffee
- Tea
- Water
- Milk
After appending:
- Coffee
- Tea
- Milk
- Water
Try it Yourself
Example
Create a <p> element and append it to a <div> element:
var para = document.createElement("P"); // Create a
<p> node
var t =
document.createTextNode("This is a paragraph.");
// Create a text node
para.appendChild(t);
// Append the text to <p>
document.getElementById("myDIV").appendChild(para);
// Append <p> to <div> with id="myDIV"
Try it Yourself
Example
Create a <p> element with some text and append it to the end of the document body:
var x = document.createElement("P"); // Create a <p>
node
var t = document.createTextNode("This is a
paragraph."); // Create a text node
x.appendChild(t);
// Append the text to <p>
document.body.appendChild(x);
// Append <p> to <body>
Try it Yourself
Related Pages
CompletedHTML DOM reference: element.hasChildNodes() Method
HTML DOM reference: element.insertBefore() Method
HTML DOM reference: element.removeChild() Method
HTML DOM reference: element.replaceChild() Method
HTML DOM reference: document.createElement() Method
HTML DOM reference: document.createTextNode() Method
HTML DOM reference: document.adoptNode() Method
