HTML DOM insertBefore() Method

Element Object


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>
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.

insertBefore() Yes Yes Yes Yes Yes


node.insertBefore(newnode, existingnode)

Parameter Values

Parameter Type Description
newnode Node object Required. The node object you want to insert
existingnode Node object Required. The child node you want to insert the new node before. If set to null, 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

More Examples


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]);
Try it Yourself »

Element Object