JavaScript/DOM: insertAfter a Element

By Xah Lee. Date: . Last updated: .

This page shows how to use JavaScript to insert a element after a given element.

The Problem

In JavaScript/DOM, there's the method “insertBefore”. But what if you want to insert after a element?

If you are not familiar with “insertBefore”, see: JS: Create HTML Element.

Solution

Use the method “insertBefore” with a second parameter that point to a sibling node. Like this:

referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);

If next sibling doesn't exist, it would still work, because the referenceNode.nextSibling will return “null”, and JavaScript will just append to last child of parent node.

Here's a full example:

// -*- coding: utf-8 -*-

// create your new node <p>Hi</p>
 var newNode = document.createElement("p");
 newNode.appendChild(document.createTextNode("Hi"));

// a existing node for reference
var refNode = document.getElementById("xyz");

// insert newNode before refNode
// refNode.parentNode.insertBefore(newNode, refNode);

// insert newNode after refNode
refNode.parentNode.insertBefore(newNode, refNode.nextSibling);

Note: when you create a node in DOM, it can exist only in one place. You can not insert it both before and after. If you want to insert the same node in multiple places, you can create a copy first by newNode.cloneNode(true).

Thanks to karim79 and Phrogz for helping on this question. Source stackoverflow.comSource stackoverflow.com

Like what you read? Buy JavaScript in Depth