HTML DOM insertBefore() Method

Element Object Reference Element Object

Example

Insert a new <li> element before the first child element of an <ul> element:

var newItem = document.createElement("LI");       // Create a <li> node
var textnode = document.createTextNode("Water");  // Create a text node
newItem.appendChild(textnode);                    // Append the text to <li>

var list = document.getElementById("myList");    // Get the <ul> element to insert a new node
list.insertBefore(newItem, list.childNodes[0]);  // Insert <li> before the first child of <ul>

Before inserting:

  • Coffee
  • Tea

After inserting:

  • Water
  • Coffee
  • Tea

Try it yourself »

More "Try it Yourself" examples below.


Definition and Usage

The insertBefore() method inserts a node as a child, right before an existing child, which you specify.

Tip: If you want to create a new list item, with text, remember to create the text as a Text node which you append to the <li> element, then insert <li> to the list.

You can also use the insertBefore method to insert/move an existing element (See "More Examples").


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
insertBefore() 1.0 Yes 1.0 Yes Yes

Syntax

node.insertBefore(newnode,existingnode)

Parameter Values

Parameter Type Description
newnode Node object Required. The node object you want to insert
existingnode Node object Optional. The child node you want to insert the new node before. When not specified, the insertBefore method will insert the newnode at the end

Technical Details

Return Value: A Node Object, representing the inserted node
DOM Version Core Level 1 Node Object

Examples

More Examples

Example

Move a <li> element from one list to another:

var node = document.getElementById("myList2").lastChild;
var list = document.getElementById("myList1");
list.insertBefore(node, list.childNodes[0]);

Before inserting:

  • Coffee
  • Tea
  • Water
  • Milk

After insertBefore:

  • Milk
  • Coffee
  • Tea
  • Water

Try it yourself »

Element Object Reference Element Object


SHARE THIS PAGE

COLOR PICKER

colorpicker





Search w3schools.com:

Translate w3schools.com: