Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

HTML DOM insertBefore method

HTML DOM insertBefore() method

Element Object Reference Element object

Example

Add an item to a list:

document.getElementById("myList").insertBefore(

newItem,existingItem

);

Before adding:

After adding:

Try it »


Definition and Usage

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

Tip: If you want to create a new text list item, you should add the element's text node after the LI element, then add the LI element to the list.

You can also use the insertBefore method to insert/remove an existing element.

Example

Move a list item to another list item:

var node=document.getElementById("myList2").lastChild;

var list=document.getElementById("myList1");

list.insertBefore(node,list.childNodes[0]);

Before adding:

After adding:

Try it »


Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the insertBefore() method


Syntax

node

.insertBefore(

newnode,existingnode

)

Parameters

Parameters Type Description
newnode Node object Required. The node object to insert
existingnode Node object Required. The child node before which the new node is added.

Return Value

Type Description
Node object The node you inserted/td>

Technical Details

DOM version Core Level 1 Node Object

Element Object Reference Element object