let childNodes = x.childNodes;
if(childNodes[0])
x.replaceChild(myIMG, childNodes[0]);
else
x.appendChild(myIMG);
that should work like a charm
We start by selecting all the child elements of X, and then we verify if the first one is defined. If there are multiple child elements, you can also use x.innerHTML method to remove them at once. If it's defined, we replace it with our new element, otherwise we simply add the element.
NOTE: If you continuously create and append elements in a loop, your script might become heavy. Since you're only changing the image inside X, consider updating the .src attribute directly instead.
let childElements = x.childNodes;
let myIMG;
if(childElements[0]) {
myIMG = childElements[0]; //make sure this is actually an image
//you may want to verify its type.
} else {
myIMG = document.createElement("img");
myIMG.src = "image-source";
x.appendChild(myIMG);
}
//now for the loop
while( your_condition )
myIMG.src = "new-image-source";
This way, you're simplifying your script by focusing on just one element.