How to swap DOM child nodes in JavaScript?

There is no need for cloning. You can just move one node before the other with this:

childNode[4].parentNode.insertBefore(childNode[4], childNode[3]);

You get the parent of the node. You then call the insertBefore method on the parent and you pass it the childNode[4] node and tell it you want it inserted before childNode[3]. That will give you the result of swapping their order so 4 will be before 3 when it's done.

Reference documentation on insertBefore.

Any node that is inserted into the DOM that is already in the DOM is first removed automatically and then inserted back so there is no need to manually remove it first.


Use .before or .after!

This is vanilla JS!

childNode[3].before(childNode[4]);

or

childNode[4].after(childNode[3]);

For more durability swapping, try:

function swap(node1, node2) {
    const afterNode2 = node2.nextElementSibling;
    const parent = node2.parentNode;
    node1.replaceWith(node2);
    parent.insertBefore(node1, afterNode2);
}

This should work, even if the parents don't match

Can I Use - 94% Aug 2020


Answer by jfriend00 does not really swap elements (it "swaps" only elements which are next to each other and only under the same parent node). This is ok, since this was the question.

This example swaps elements by cloning it but regardless of their position and DOM level:

// Note: Cloned copy of element1 will be returned to get a new reference back
function exchangeElements(element1, element2)
{
    var clonedElement1 = element1.cloneNode(true);
    var clonedElement2 = element2.cloneNode(true);

    element2.parentNode.replaceChild(clonedElement1, element2);
    element1.parentNode.replaceChild(clonedElement2, element1);

    return clonedElement1;
}

Edit: Added return of new reference (if you want to keep the reference, e. g. to access attribute "parentNode" (otherwise it gets lost)). Example: e1 = exchangeElements(e1, e2);