/html-dom /Basic
GitHub 4932★

Swap two nodes

The function below swaps two given nodes, nodeA and nodeB:

const swap = function (nodeA, nodeB) {
const parentA = nodeA.parentNode;
const siblingA = nodeA.nextSibling === nodeB ? nodeA : nodeA.nextSibling;

// Move `nodeA` to before the `nodeB`
nodeB.parentNode.insertBefore(nodeA, nodeB);

// Move `nodeB` to before the sibling of `nodeA`
parentA.insertBefore(nodeB, siblingA);
};

See also

Follow me on and to get more useful contents.