时间:2021-07-01 10:21:17 帮助过:21人阅读
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, firsChild); //替换第一个元素,返回被替换掉的元素
alert(returnNode.innerHTML); //1
var lastChild = oDiv.lastElementChild ? oDiv.lastElementChild : oDiv.lastChild;
oSpan = document.createElement("span");
oSpan.innerHTML = "5";
returnNode = oDiv.replaceChild(oSpan, lastChild); //替换最后一个,返回被替换掉的元素
alert(returnNode.innerHTML);//3
代码如下:
<div id="guoDiv">
<span>1</span>
<span>2</span>
<span>3</span>
</div>