replaceChild(a,b) is used to replace existing elements in the document.
Parameter a: the node to be inserted,
Parameter b: The node to be replaced
The code copy is as follows:
var oDiv = document.getElementById("guoDiv");
var oSpan = document.createElement("span");
oSpan.innerHTML = "4";
var firsChild = oDiv.firstElementChild ? oDiv.firstElementChild : oDiv.firstChild
var returnNode = oDiv.replaceChild(oSpan, firstChild); //Replace the first element and return the replaced element
alert(returnNode.innerHTML); //1
var lastChild = oDiv.lastElementChild ? oDiv.lastElementChild : oDiv.lastChild;
oSpan = document.createElement("span");
oSpan.innerHTML = "5";
returnNode = oDiv.replaceChild(oSpan, lastChild); //Replace the last one, return the replaced element
alert(returnNode.innerHTML);//3
The code copy is as follows:
<div id="guoDiv">
<span>1</span>
<span>2</span>
<span>3</span>
</div>