JAVASCRIPT
Insert DOM Elements Before or After Others
Discover how to precisely insert new HTML elements into the DOM relative to an existing reference element, either before it using `insertBefore` or after it.
const referenceElement = document.getElementById('referenceItem');
const parentContainer = referenceElement ? referenceElement.parentNode : null;
if (parentContainer && referenceElement) {
// Create a new element to insert before
const elementBefore = document.createElement('li');
elementBefore.textContent = 'New item BEFORE reference';
elementBefore.style.color = 'blue';
// Create a new element to insert after
const elementAfter = document.createElement('li');
elementAfter.textContent = 'New item AFTER reference';
elementAfter.style.color = 'green';
// Insert 'elementBefore' directly before the 'referenceElement'
parentContainer.insertBefore(elementBefore, referenceElement);
// Insert 'elementAfter' directly after the 'referenceElement'
// There's no native insertAfter, so we insert before the next sibling.
if (referenceElement.nextElementSibling) {
parentContainer.insertBefore(elementAfter, referenceElement.nextElementSibling);
} else {
// If there's no next sibling, append it to the end of the parent
parentContainer.appendChild(elementAfter);
}
} else {
console.warn('Reference element or its parent not found.');
}
How it works: This snippet illustrates how to insert new elements into the DOM relative to an existing element. `parentNode.insertBefore(newElement, referenceElement)` is used to place `newElement` directly before `referenceElement`. To insert an element *after* a reference, a common workaround is used: check for the `referenceElement`'s `nextElementSibling`. If it exists, the new element is inserted before that sibling; otherwise, it's appended to the parent, effectively placing it after the reference.