HTML DOM Element insertBefore() Method

Definition and Usage

insertBefore() The method inserts a child node before an existing child node.

See also:

appendChild() method

replaceChild() method

removeChild() method

remove() method

childNodes attribute

firstChild attribute

lastChild attribute

firstElementChild attribute

lastElementChild attribute

Instance

Example 1

  1. Create an <li> element
  2. Create a text node
  3. Attach text to the <li> element
  4. Insert the <li> element before the first child element in <ul>:
const newNode = document.createElement("li");
const textNode = document.createTextNode("Water");
newNode.appendChild(textNode);
const list = document.getElementById("myList");
list.insertBefore(newNode, list.children[0]);

Try It Yourself

Example 2

Move the last element from one list to the beginning of another list:

const node = document.getElementById("myList2").lastElementChild;
const list = document.getElementById("myList1");
list.insertBefore(node, list.children[0]);

Try It Yourself

Example 3

Move the last element from one list to the end of another list:

const node = document.getElementById("myList2").lastElementChild;
const list = document.getElementById("myList1");
list.insertBefore(node, null);

Try It Yourself

Syntax

element.insertBefore(newnode, existingnode)

or

node.insertBefore(newnode, existingnode)

Parameter

Parameter Description
newnode Required. The node to be inserted (element).
existingnode

Optional. Insert a new node before the existing node.

If not specified, the insertBefore method will insert newnode at the end.

Return Value

Type Description
Node The node to be inserted.

Browser Support

element.insertBefore() It is a DOM Level 1 (1998) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support