The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node.
If the given node already exists in the document, insertBefore() moves it from its current position to the new position. (That is, it will automatically be removed from its existing parent before appending it to the specified new parent.)
This means that a node cannot be in two locations of the document simultaneously.
Note: The Node.cloneNode() can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode() will not be automatically kept in sync.
If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node.
insertBefore(newNode, referenceNode)
Returns the added child (unless newNode is a DocumentFragment, in which case the empty DocumentFragment is returned).
<div id="parentElement">
<span id="childElement">foo bar</span>
</div>
<script>
const newNode = document.createElement("span");
const parentDiv = document.getElementById("childElement").parentNode;
let sp2 = document.getElementById("childElement");
parentDiv.insertBefore(newNode, sp2);
sp2 = undefined;
parentDiv.insertBefore(newNode, sp2);
sp2 = "undefined";
parentDiv.insertBefore(newNode, sp2);
</script>
<div id="parentElement">
<span id="childElement">foo bar</span>
</div>
<script>
let sp1 = document.createElement("span");
let sp2 = document.getElementById("childElement");
let parentDiv = sp2.parentNode;
parentDiv.insertBefore(sp1, sp2);
</script>
Note: There is no insertAfter() method. It can be emulated by combining the insertBefore method with Node.nextSibling.
In the previous example, sp1 could be inserted after sp2 using:
parentDiv.insertBefore(sp1, sp2.nextSibling);
If sp2 does not have a next sibling, then it must be the last child — sp2.nextSibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2).
Insert an element before the first child element, using the firstChild property.
let parentElement = document.getElementById("parentElement");
let theFirstChild = parentElement.firstChild;
let newElement = document.createElement("div");
parentElement.insertBefore(newElement, theFirstChild);
When the element does not have a first child, then firstChild is null. The element is still appended to the parent, after the last child.
Since the parent element did not have a first child, it did not have a last child, either. Consequently, the newly inserted element is the only element.