// The following helper function insertAfter() lets you insert a new element after an existing one in the DOM tree:
function insertAfter(el, referenceNode) {
referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling);
}
// example
var newEl = document.createElement('div');
newEl.innerHTML = '<p>Hello World!</p>';
var ref = document.querySelector('div.before');
insertAfter(newEl, ref);
// To insert an element before another one, we can use a very similar helper function: insertBefore()
function insertBefore(el, referenceNode) {
referenceNode.parentNode.insertBefore(el, referenceNode);
}
// example
var newEl = document.createElement('div');
newEl.innerHTML = '<p>Hello World!</p>';
var ref = document.querySelector('div.before');
insertBefore(newEl, ref);