javascript insertAfter of Definition and Usage Examples

  • 2021-07-04 18:14:37
  • OfStack

This article illustrates the definition and usage of javascript insertAfter (). Share it for your reference, as follows:

HTML section:


<div id="b">bbbbbbbbb</div>
<div>dddddd</div>

JavaScript section:


window.onload=function(){
  var a =document.createElement("span");
  var b =document.createTextNode("cssrain");
  a.appendChild(b);
  var mubiao = document.getElementById("b");
  insertAfter(a,mubiao); 
}
function insertAfter(newElement,targetElement) {
  var parent = targetElement.parentNode;
   if (parent.lastChild == targetElement) {//  If the last node is the target element, it is added directly. Because the default is last 
    parent.appendChild(newElement);
   } else {
    parent.insertBefore(newElement,targetElement.nextSibling);// If not, insert under the target element 1 In front of the sibling nodes. That is, after the target element. 
   }
}

More readers interested in JavaScript can check the topics of this site: "Summary of Common Function Skills of JavaScript", "Summary of Switching Special Effects and Skills of JavaScript", "Summary of Search Algorithm Skills of JavaScript", "Summary of Animation Special Effects and Skills of JavaScript", "Summary of Error and Debugging Skills of JavaScript", "Summary of Data Structure and Algorithm Skills of JavaScript", "Summary of Traversal Algorithm and Skills of JavaScript" and "Summary of Mathematical Operation Usage of JavaScript"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: