Parent Element .appendChild() Since: DOM Level 1(1998)
Appends the specified HTML element as the last child of a parent element. Commonly used to insert an element created with document.createElement() into the DOM.
Syntax
parentElement.appendChild(elementToAdd);
Parameters
| Parameter | Description |
|---|---|
| elementToAdd | The HTML element (Element object) to append at the end of the parent element. |
Return Value
Returns the appended HTML element (the same element passed as the argument).
Sample Code
<ul id="list"> <li>Item 1</li> <li>Item 2</li> </ul>
var list = document.querySelector("#list");
// Create a new HTML element and append it.
var newItem = document.createElement("li");
newItem.textContent = "Item 3";
list.appendChild(newItem);
// Result: Item 1, Item 2, Item 3
// Append multiple HTML elements in sequence.
var fruits = ["Apple", "Orange", "Grape"];
fruits.forEach(function(name) {
var li = document.createElement("li");
li.textContent = name;
list.appendChild(li);
});
Description
parentElement.appendChild() is the fundamental method for adding an element to the DOM. The element is inserted at the end of the target parent element (after its last child).
Note: if you call parentElement.appendChild() on an element that already exists in the DOM, it is removed from its original position and moved to the new location. Because this is a move rather than a copy, if you need to place the same element in multiple locations, clone it first with cloneNode(true) and then append the clone.
To insert an element at a specific position rather than at the end, use insertBefore().
Browser Compatibility
1 or earlier ×
4 or earlier ×
6 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.