This article mainly introduces how to use javascript to replace existing elements with replaceChild (). For more information, see replaceChild (a, B ).
Parameter a: the node to be inserted,
Parameter B: the node to be replaced
The 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
The Code is as follows:
1
2
3