How to insert an element after another element in JavaScript without using a library?
There's insertBefore()
in JavaScript, but how can I insert an element after another element without using jQuery or another 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
/* Adds Element BEFORE NeighborElement */
Element.prototype.appendBefore = function(element) {
element.parentNode.insertBefore(this, element);
}, false;
/* Adds Element AFTER NeighborElement */
Element.prototype.appendAfter = function(element) {
element.parentNode.insertBefore(this, element.nextSibling);
}, false;
/* Typical Creation and Setup A New Orphaned Element Object */
var NewElement = document.createElement('div');
NewElement.innerHTML = 'New Element';
NewElement.id = 'NewElement';
/* Add NewElement BEFORE -OR- AFTER Using the Aforementioned Prototypes */
NewElement.appendAfter(document.getElementById('Neighbor2'));
div {
text-align: center;
}
#Neighborhood {
color: brown;
}
#NewElement {
color: green;
}
<div id="Neighborhood">
<div id="Neighbor1">Neighbor 1</div>
<div id="Neighbor2">Neighbor 2</div>
<div id="Neighbor3">Neighbor 3</div>
</div>
Run it on JSFiddle
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/insertAdjacentElement https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText
insertAdjacentHTML
+ outerHTML
elementBefore.insertAdjacentHTML('afterEnd', elementAfter.outerHTML)
Upsides:
- DRYer: you don't have to store the before node in a variable and use it twice. If you rename the variable, on less occurrence to modify.
- golfs better than the
insertBefore
(break even if the existing node variable name is 3 chars long)
Downsides:
- lower browser support since newer: https://caniuse.com/#feat=insert-adjacent
- will lose properties of the element such as events because
outerHTML
converts the element to a string. We need it becauseinsertAdjacentHTML
adds content from strings rather than elements.
A quick Google search reveals this script
// create function, it expects 2 values.
function insertAfter(newElement,targetElement) {
// target is what you want it to go after. Look for this elements parent.
var parent = targetElement.parentNode;
// if the parents lastchild is the targetElement...
if (parent.lastChild == targetElement) {
// add the newElement after the target element.
parent.appendChild(newElement);
} else {
// else the target has siblings, insert the new element between the target and it's next sibling.
parent.insertBefore(newElement, targetElement.nextSibling);
}
}