JAVASCRIPT
Swap Positions of Two Sibling DOM Elements
Learn to programmatically exchange the positions of two sibling elements within their parent container using `insertBefore`, enabling dynamic reordering of content.
/**
* Swaps the positions of two sibling DOM elements.
* Both elements must share the same parent.
* @param {HTMLElement} element1 The first element to swap.
* @param {HTMLElement} element2 The second element to swap.
*/
function swapElements(element1, element2) {
if (!element1 || !(element1 instanceof HTMLElement) || !element2 || !(element2 instanceof HTMLElement)) {
console.error('Invalid elements provided to swapElements.');
return;
}
if (element1.parentNode !== element2.parentNode) {
console.error('Elements must be siblings to be swapped.');
return;
}
const parent = element1.parentNode;
const nextSiblingOfElement2 = element2.nextSibling;
// Insert element1 before element2
parent.insertBefore(element1, element2);
// Insert element2 before the original next sibling of element1
// If element1 was originally next to element2, then element2.nextSibling would be null or the element after element1.
// After the first insert, element1 is now before element2. We need to place element2
// where element1 was, effectively. The original nextSiblingOfElement2 ensures correct placement.
parent.insertBefore(element2, nextSiblingOfElement2);
}
// Example Usage:
// Assuming <div id="parent"><span id="first">First</span><span id="second">Second</span></div>
// const first = document.getElementById('first');
// const second = document.getElementById('second');
// swapElements(first, second); // Parent content becomes: <span id="second">Second</span><span id="first">First</span>
How it works: This function allows you to swap the positions of two sibling DOM elements within their common parent. It achieves this by first storing a reference to the element immediately following the second element (`nextSiblingOfElement2`). Then, it uses `insertBefore()` to place the first element before the second. Finally, it places the second element before the stored reference, effectively moving it to the original position of the first element. This technique dynamically reorders elements without recreating them.