JavaScript: appendChild
The appendChild() method adds one existing node to the end of a parent element.
What you will learn
- How to create and append a new element
- Where the new node is inserted
- How appendChild differs from append
Minimal example
const list = document.querySelector('#list');
const item = document.createElement('li');
item.textContent = 'New item';
if (list) list.appendChild(item);The new li is placed after the existing children of #list. The method returns the node that was appended.
appendChild and append
appendChild() accepts one Node and returns it. Element.append() can add multiple Nodes or strings, but it does not return the appended value. Choose the method that matches what you need.
Common mistakes
- Create a Node with
document.createElement(); a string is not automatically converted to an element. - If the node already belongs to another parent, appendChild moves it rather than copying it.
- Check that the parent element exists before appending.