Favorites

DOM Node.insertBefore() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
Node.insertBefore()
DOM Node MethodThis method is supported by all modern browsers.
Updated 28th November 2026

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 null to add at the end.

Return Value

The inserted node.

Example

<ul id="list">
  <li>One</li>
  <li>Two</li>
</ul>
const list = document.getElementById('list');
const first = document.createElement('li');
first.textContent = 'Zero';
list.insertBefore(first, list.firstElementChild);
console.log(list.textContent.trim().split(/\s+/));

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.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee