insertBefore (W3C DOM Core method)

Spec
Version Depr. Static
DOM1 No No
Browser support (more…)
IE5.5+ FF1.5+ SA1.3+ OP9+
Full Full Full Full
Returns
Node
Throws
HIERARCHY_REQUEST_ERR, WRONG_DOCUMENT_ERR, NO_MODIFICATION_ALLOWED_ERR, NOT_FOUND_ERR

Example

node.insertBefore(newnode, existingchild);

The example above will append newnode as a child of node, directly before the existingchild node.

So in the following HTML example, let's say that node is the p element and existingchild is the em element inside it:

<p>Pour some sugar on it <em>don't be shy</em></p>

Then if newnode is a text node with the value honey, , the insert operation would result in this:

<p>Pour some sugar on it honey, <em>don't be shy</em></p>

Arguments

new node (Node) required

The new node to insert.

existing child (Node) required

An existing child node that the new node should be inserted before. If this argument is null, the new node is inserted at the end of this node's list of children.

Description

Insert a new node as a child of this node, directly before an existing child of this node, or at the end of the list of children if no existing child is specified or it's null. If the new child is already present in the DOM tree it is first removed (effectively moving it).

Tip: How to remember the syntax

This method is fantastically useful, but it can be tricky to remember the syntax. I remember it as a little sentence, like this: "into parent, insert new before old".

If you don't have a parent reference, it's easy to extrapolate one from the node you do have:

old.parentNode.insertBefore(new, old);

Conversely, if you only have a parent reference you can still insert at the beginning (providing that the parent has at least one child node already):

parent.insertBefore(new, parent.firstChild);

Or the end (which is exactly equivalent to appendChild):

parent.insertBefore(new, null);

Return value

The node that was inserted

Compatibility

Internet Explorer Firefox Safari Opera
5.5 6.0 7.0 1.5 2.0 3.0 1.3 2.0 3.0 9.0 9.5
Full Full Full Full Full Full Full Full Full Full Full

No known issues.

User-contributed notes

There are no comments yet.

Related Products