insertBefore (W3C DOM Core method)
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>
if newnode is a text node with the value
honey, , the insert operation would result in
<p>Pour some sugar on it honey, <em>don't be shy</em></p>
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:
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):
Or the end (which is exactly equivalent to
The node that was inserted
No known issues.
There are no comments yet.