insertBefore (W3C DOM Core method)
| Version | Depr. | Static |
|---|---|---|
| DOM1 | No | No |
| 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
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).
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.
Add a note
To post a note on this topic, please log in with your SitePoint username and password. If you don't have an account yet, you can create a new account for free.