plainJS

Functions / Manipulation

Insert an element after or before another

jQuery $.after(), $.before(), $.insertAfter(), $.insertBefore

2015 page

This is the original page from 2015, kept at its address while the tested rewrite is in progress. The code is of its time: it ran in Internet Explorer and does not use what browsers have gained since. The rewrite replaces it here.

In short

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

The following helper function insertAfter() lets you insert a new element after an existing one in the DOM tree:

js
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()

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

These DOM methods are supported by all major browsers, including IE 8 and below.

If you intend to insert a new structure in form of an HTML text string, you should make use of insertAdjacentHTML(). This method parses the specified text as HTML and inserts the resulting elements into the DOM tree at a specified position. It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element.