Swapping two children of a parent node in JS

I have a parent div of nine divs, that each has a different background image. My task is to, whenever, I click on any of the divs except the targetDiv, the div gets swapped by the targetDiv in the DOM. So, here is the code:

function swap(e){
    let parent=document.getElementsByClassName('container')[0];
    swapDivsByBackground(parent,e.style.background);
}

function swapDivsByBackground(parent, bgImage1) {

    const children = Array.from(parent.children);
    const moveDiv = children.find(div => div.style.background.includes(bgImage1));
    if(!moveDiv) 
        return;

    const moveIndex = children.indexOf(moveDiv);
    const targetIndex = children.indexOf(targetDiv);

    parent.removeChild(moveDiv);
    parent.removeChild(targetDiv);
    
try{
    parent.insertBefore(moveDiv, children[moveIndex+1] || null);
}
catch(e){
    console.log(moveIndex+1);
    console.log(children[moveIndex+1]);
    console.log(e.message);
}
try{
    parent.insertBefore(targetDiv, children[targetIndex+1] || null);
}
catch(e){
    console.log(targetIndex+1);
    console.log(children[targetIndex+1]);
    console.log(e.message);
}
}

I am seriously facing some issues here. Sometimes, there are no swaps, and sometimes, I even get a error that says:

Failed to execute ‘insertBefore’ on ‘Node’: The node before which the new node is to be inserted is not a child of this node.

But alongside, I also receive the console messages from console.log(moveIndex+1); and console.log(children[moveIndex+1]);, that shows a valid div reference. But, if the node is not a child, then why are these messages shown? They should have shown undefined.