HomeMathComputingArtsWordsLiteratureMusictwitter facebook webfeed

Javascript/DOM: insertAfter a Element

Xah Lee, 2011-01-26

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

Advertise Here For Profit

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: Inserting HTML Content With Javascript.

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 js 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);

Here's a test page: javascript test insert after.

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

blog comments powered by Disqus