Insert an element after or before another
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:
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);
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.