Javascript to replace the existing element replaceChild of use

  • 2020-03-30 02:30:39
  • OfStack

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
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 element that was replaced

<div id="guoDiv"> 

Related articles: