DOM Node.insertBefore() Method
The insertBefore() method inserts a node into a parent element before a given child.
Description
The insertBefore() method inserts a node as a child of the parent, just before the reference child. If the reference is null, the node is added at the end. The newer before(), after() and prepend() methods are often simpler.
As with appendChild(), inserting a node that's already in the document moves it rather than copying it, and inserting a DocumentFragment inserts all of its children. There's no insertAfter() method; the usual workaround is parent.insertBefore(newNode, reference.nextSibling), which works because a null sibling means "add at the end".
The reference node must be a child of the parent, otherwise a NotFoundError is thrown. The newer before() and after() methods are called on the reference element itself, so you don't need a reference to the parent.
Syntax
parent.insertBefore(newNode, referenceNode)Parameters
- newNodeThe node to insert.
- referenceNodeThe child to insert before, or
nullto add at the end.
Return Value
The inserted node.
Example
Browser Support
The following information will show you the current browser support for the Node.insertBefore() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





