Appending Children with appendChild
You'll learn how to attach newly created or existing elements to the DOM tree using appendChild, and discover its surprising behavior with existing elements.
What appendChild Does
The appendChild method adds a child node to the end of a parent element's list of children. Think of it like placing a new toy at the bottom of a toy box — it becomes the last item inside.
Here's the basic syntax:
parentElement.appendChild(childElement);
Building DOM Structures
After creating elements with createElement, you need to actually place them somewhere in your document. That's where appendChild comes in:
// Create a new paragraph
const newParagraph = document.createElement('p');
newParagraph.textContent = 'Hello, world!';
// Add it to the body
document.body.appendChild(newParagraph);
The paragraph won't appear on your page until you append it to an existing element in the DOM tree.
The Moving Behavior
Here's the surprising part: if you append an element that's already in the DOM, it moves rather than duplicates. It's like picking up that toy from the toy box and placing it back on top — there's still only one toy, just in a new position.
const existingDiv = document.getElementById('myDiv');
const container = document.querySelector('.container');
// This MOVES existingDiv to container, not copies it
container.appendChild(existingDiv);
This behavior is useful when reorganizing your page structure without creating duplicates.
Building Nested Structures
You can build complex hierarchies by chaining appendChild calls:
const article = document.createElement('article');
const heading = document.createElement('h2');
heading.textContent = 'My Article';
article.appendChild(heading);
document.body.appendChild(article);
Key Takeaway: appendChild attaches elements to the end of a parent's children list and automatically moves (not copies) elements that already exist elsewhere in the DOM.