JAVASCRIPT

Swap Position of Two Sibling DOM Elements

Learn to programmatically change the order of two direct sibling elements within their parent container using JavaScript's `insertBefore` method and conditional logic.

/**
 * Swaps the position of two direct sibling elements in the DOM.
 * @param {HTMLElement} element1 The first sibling element to swap.
 * @param {HTMLElement} element2 The second sibling element to swap.
 */
function swapElements(element1, element2) {
  if (!element1 || !element2 || element1.parentNode !== element2.parentNode) {
    console.error('Both elements must be valid and direct siblings.');
    return;
  }

  const parent = element1.parentNode;
  const nextSiblingOfE1 = element1.nextElementSibling;
  const nextSiblingOfE2 = element2.nextElementSibling;

  // If element1 is immediately before element2
  if (nextSiblingOfE1 === element2) {
    parent.insertBefore(element2, element1);
  }
  // If element2 is immediately before element1
  else if (nextSiblingOfE2 === element1) {
    parent.insertBefore(element1, element2);
  }
  // If they are not adjacent
  else {
    parent.insertBefore(element2, nextSiblingOfE1);
    parent.insertBefore(element1, nextSiblingOfE2);
  }
}

// --- Example Usage ---
// Assume HTML:
// <div id="items-container">
//   <p id="first" class="draggable">First Item</p>
//   <p id="second" class="draggable">Second Item</p>
//   <p id="third" class="draggable">Third Item</p>
//   <p id="fourth" class="draggable">Fourth Item</p>
// </div>
// <button onclick="performSwap('first', 'third')">Swap First & Third</button>
// <button onclick="performSwap('second', 'first')">Swap Second & First</button>

function performSwap(id1, id2) {
  const el1 = document.getElementById(id1);
  const el2 = document.getElementById(id2);
  if (el1 && el2) {
    console.log(`Swapping ${id1} and ${id2}`);
    swapElements(el1, el2);
  } else {
    console.error('One or both elements not found.');
  }
}
How it works: The `swapElements` function provides a way to reorder two sibling elements within their common parent. It intelligently uses `insertBefore` by determining the current positions of the elements and their next siblings. This allows for swapping both adjacent and non-adjacent sibling elements, which is useful for features like drag-and-drop interfaces or dynamic list reordering without removing and re-adding elements.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs