HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to insert an element after another element in JavaScript without using a library?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
inserthowusingelementlibrarywithoutafterjavascriptanother

Problem

There's insertBefore() in JavaScript, but how can I insert an element after another element without using jQuery or another library?

Solution

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(referenceNode, newNode) {
    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);

Hello

Code Snippets

referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

Context

Stack Overflow Q#4793604, score: 1740

Revisions (0)

No revisions yet.