How to insert an element after another element in JavaScript without using a library?
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
Where referenceNode
is the node you want to put newNode
after. If referenceNode
is the last child within its parent element, that's fine, because referenceNode.nextSibling
will be null
and insertBefore
handles that case by adding to the end of the list.
So:
function insertAfter(newNode, referenceNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);}
You can test it using the following snippet:
function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);}var el = document.createElement("span");el.innerHTML = "test";var div = document.getElementById("foo");insertAfter(div, el);
<div id="foo">Hello</div>
Straightforward JavaScript Would Be the Following:
Append Before:
element.parentNode.insertBefore(newElement, element);
Append After:
element.parentNode.insertBefore(newElement, element.nextSibling);
But, Toss Some Prototypes In There For Ease of Use
By building the following prototypes, you will be able to call these function directly from newly created elements.
newElement.appendBefore(element);
newElement.appendAfter(element);
.appendBefore(element) Prototype
Element.prototype.appendBefore = function (element) { element.parentNode.insertBefore(this, element);},false;
.appendAfter(element) Prototype
Element.prototype.appendAfter = function (element) { element.parentNode.insertBefore(this, element.nextSibling);},false;
And, To See It All In Action, Run the Following Code Snippet
Though insertBefore() is great and referenced by most answers here. For added flexibility, and to be a little more explicit, you can use:
The insertAdjacentElement() as refElem.insertAdjacentElement(position, newElem)
lets you reference any element, and insert the to-be moved element exactly where you want (position can be one of: 'beforebegin'
, 'afterbegin'
, 'beforeend'
, 'afterend'
) as shown below:
// refElem.insertAdjacentElement('beforebegin', myElem); <p id="refElem"> // refElem.insertAdjacentElement('afterbegin', myElem); ... content ... // refElem.insertAdjacentElement('beforeend', myElem);</p>// refElem.insertAdjacentElement('afterend', myElem);
Others to consider for similar use cases: insertAdjacentHTML()
and insertAdjacentText()
References:
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElementhttps://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTMLhttps://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText