ajpenalosa
12/21/2017 - 3:15 AM

Insert an element after or before another

Insert an HTML structure after or before a given DOM tree element.

https://plainjs.com/javascript/manipulation/insert-an-element-after-or-before-another-32/

// 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);