JAVASCRIPT
Insert Element Before Sibling
Learn to dynamically insert a new HTML element right before an existing sibling element within the DOM, useful for flexible content arrangement on the fly.
function insertBeforeSibling(newElementHtml, targetElementId) {
const targetElement = document.getElementById(targetElementId);
if (targetElement && targetElement.parentNode) {
const newElementContainer = document.createElement('div'); // Use a container to parse HTML string
newElementContainer.innerHTML = newElementHtml;
const newElement = newElementContainer.firstElementChild; // Get the actual new element
if (newElement) {
targetElement.parentNode.insertBefore(newElement, targetElement);
} else {
console.warn('Could not parse new element from HTML string.');
}
} else {
console.warn(`Target element with ID ${targetElementId} not found or has no parent.`);
}
}
// Usage:
insertBeforeSibling('<h3>New Title Here</h3><p>Some fresh content.</p>', 'existingSection');
How it works: This function dynamically creates a new HTML element from a provided HTML string and inserts it immediately before a specified target sibling element in the DOM. It first parses the HTML string into a temporary container, then uses `parentNode.insertBefore()` to position the newly created element correctly, offering precise control over DOM structure modification.