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
Copy codeThe Code 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, firsChild); // 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 and return the replaced element.
Alert (returnNode. innerHTML); // 3
Copy codeThe Code is as follows:
<Div id = "guoDiv">
<Span> 1 </span>
<Span> 2 </span>
<Span> 3 </span>
</Div>