Modern Insertion Methods: append and prepend
You'll learn how to use simpler, more flexible DOM insertion methods that can handle both elements and text in one go.
The Old Way vs The Modern Way
You've already learned appendChild and insertBefore, which work great but have limitations: they only accept a single node at a time, and you must create text nodes separately when adding text. Modern methods like append() and prepend() simplify this process dramatically.
Think of it like packing a box: The old way requires you to wrap each item individually before placing it. The new way lets you toss in items and text directly, all at once.
The Four Modern Methods
append() adds one or more nodes or strings to the end of a parent element:
const container = document.getElementById('box');
const newElement = document.createElement('p');
// Add element AND text in one call
container.append(newElement, 'Some text here');
prepend() adds content to the beginning of a parent element:
container.prepend('This appears first', newElement);
before() inserts content before an element (as a sibling):
const heading = document.querySelector('h1');
heading.before('New text before heading');
after() inserts content after an element (as a sibling):
heading.after(newElement, 'More text');
Key Advantages
- Accept multiple arguments at once
- Handle strings directly (no need for
createTextNode) - More readable syntax that matches your intent
- Can mix elements and text in a single call
Key Takeaway: Modern insertion methods (append, prepend, before, after) simplify DOM manipulation by accepting multiple items—both elements and strings—in a single, readable call.