The original way to add elements to the DOM. Call it on the parent of the element you’re inserting your new element before (the referenceNode
), and pass in both the new element and the reference node as arguments.
// Create a new element
var newNode = document.createElement('div');
// Get the reference node
var referenceNode = document.getElementById('some-element');
// Insert the new node before the reference node
referenceNode.parentNode.insertBefore(newNode, referenceNode);
You can also use it to inject an element after another one by using the .nextSibling
property on your referenceNode
.
// Create a new element
var newNode = document.createElement('div');
// Get the reference node
var referenceNode = document.getElementById('#some-element');
// Insert the new node after the reference node
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
Source
https://vanillajstoolkit.com/reference/dom-injection/element-insertbefore/