Xah Lee Xah Lee - 3 months ago 11
Javascript Question

How to do insert After() in JavaScript without using a library?

There's

insertBefore()
in JavaScript, but how to do insert after a element without using jQuery or other library?

Answer
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);
}

Try it here.

Comments