JAVASCRIPT
Inserting, Replacing, and Removing DOM Elements Precisely
Learn to precisely manipulate DOM elements by inserting new ones before or after existing nodes, replacing elements, or removing them entirely using JavaScript.
<div id="container">
<p id="first">First paragraph</p>
<p id="target">This is the target paragraph.</p>
<p id="last">Last paragraph</p>
</div>
<script>
const container = document.getElementById('container');
const targetElement = document.getElementById('target');
// 1. Create a new element
const newParagraph = document.createElement('p');
newParagraph.textContent = 'A newly inserted paragraph.';
newParagraph.style.color = 'blue';
// 2. Insert before a target element
container.insertBefore(newParagraph, targetElement);
console.log('Inserted newParagraph before targetElement.');
// 3. Create another element to insert after
const anotherParagraph = document.createElement('p');
anotherParagraph.textContent = 'Another paragraph, inserted after.';
anotherParagraph.style.color = 'green';
// 4. Insert after a target element (using insertBefore with nextSibling)
// A more direct way: targetElement.insertAdjacentElement('afterend', anotherParagraph);
targetElement.parentNode.insertBefore(anotherParagraph, targetElement.nextSibling);
console.log('Inserted anotherParagraph after targetElement.');
// 5. Create a replacement element
const replacementParagraph = document.createElement('p');
replacementParagraph.textContent = 'This paragraph replaced the original target.';
replacementParagraph.style.fontWeight = 'bold';
// 6. Replace an element
targetElement.replaceWith(replacementParagraph);
console.log('Replaced targetElement with replacementParagraph.');
// 7. Remove an element (e.g., the 'first' paragraph)
const firstParagraph = document.getElementById('first');
if (firstParagraph) {
firstParagraph.remove();
console.log('Removed firstParagraph.');
}
</script>
How it works: This snippet demonstrates various methods for precise DOM manipulation. `parentNode.insertBefore(newNode, referenceNode)` inserts `newNode` directly before `referenceNode`. To insert after, you can use `referenceNode.nextSibling` as the reference. `element.replaceWith(newElement)` replaces the `element` itself with `newElement`. Finally, `element.remove()` is a simple and clean way to remove an element from the DOM.