EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.


[JavaScript] Insert a new div before, in the middle or behind a div

I did a project before. I can't write code with jQuery, but I can only write and insert it with native JS. The code is as follows:

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta charset="utf-8" />
div {
	border: solid 1px red;
<div id="test">current div</div>
window.onload = function () {
  //define what text will display       
  var Before = "js insert before";
  var Center = "js insert in";
  var After = "js insert after";
  //get the only element in your body
  var current = document.getElementById("test");
  //define the 'before' demo div
  var newNodeBefore = document.createElement("div");
  newNodeBefore.innerHTML = Before;
  current.parentNode.insertBefore(newNodeBefore, current);
  //define the 'middle' demo div
  var newNodeCenter = document.createElement("div");
  newNodeCenter.innerHTML = Center;
  //define the 'after' demo div
  var newNodeAfter = document.createElement("div");
  newNodeAfter.innerHTML = After;
  current.parentNode.insertBefore(newNodeAfter, current.nextSibling)

I used to use Jquery to complete the above tasks, but now the times have changed, and what JQuery can do can now be done with JavaScript. JQuery finally withdrew from the stage of history.

This article was last edited at 2020-10-24 00:49:59

* *