Inserting Elements
Inserting Elements
Section titled “Inserting Elements”Introduction
Section titled “Introduction”After creating elements, you need to insert them into the DOM. Modern methods like append and prepend are cleaner than older methods.
Classic Methods
Section titled “Classic Methods”const container = document.querySelector('.container');const element = document.createElement('p');element.textContent = 'New paragraph';
// Append as last childcontainer.appendChild(element);
// Insert at a specific position (before first child)container.insertBefore(element, container.firstChild);Modern Methods (Preferred)
Section titled “Modern Methods (Preferred)”const container = document.querySelector('.container');const element = document.createElement('p');element.textContent = 'New paragraph';
container.prepend(element); // Insert as first childcontainer.append(element); // Insert as last childcontainer.before(element); // Insert before the container itselfcontainer.after(element); // Insert after the container itselfelement.replaceWith(newElement); // Replace element with a new oneMultiple Elements at Once
Section titled “Multiple Elements at Once”// Modern methods accept multiple argumentsconst p1 = document.createElement('p');const p2 = document.createElement('p');container.append(p1, p2, 'Some text'); // Appends all threeSummary
Section titled “Summary”| Method | Position |
|---|---|
appendChild() | Last child (classic) |
insertBefore() | Before a reference node |
append() | Last child (modern) |
prepend() | First child (modern) |
before() | Before the element |
after() | After the element |
replaceWith() | Replaces the element |