Javascript insertAfter()

There is no Node.insertAfter() DOM function in Javascript, but it is clearly something that developers would like.

As the Gecko DOM Reference for Node.insertBefore() points out, this can easily be achieved with
parentDiv.insertBefore(nodeToInsert, nodeToInsertAfter.nextSibling);

If nodeToInsertAfter doesn’t have a next sibling, a NULL value will be returned and nodeToInsert will be inserted as the last child of parentDiv.

If you find it frustrating to type insertBefore when you want to insertAfter, that’s OK: you can add that function to the Object object:
Object.prototype.insertAfter = function (newNode) { this.parentNode.insertBefore(newNode, this.nextSibling); }

Now you can type:
nodeToInsertAfter.insertAfter(nodeToInsert)

5 thoughts on “Javascript insertAfter()”

  1. Additionally, for certain elements you can pass in the value “-1” before appending.
    For example:
    var row = table.insertRow(-1);
    for (var c= 0; c < 4; c++)
    {
    var cell = row.insertCell(-1);
    cell.appendChild(document.createTextNode(data[i++]));
    }

  2. Should it perhaps be added to the Node prototype, rather than the Object prototype, since the insertBefore method it is leveraging is also part of Node?

  3. Also, to be properly symmetrical, shouldn’t it be an “insertAfter” method on the _parent_, which takes a reference node just like “insertBefore” does?

Leave a Reply

Your email address will not be published. Required fields are marked *