HTML DOM insertBefore()Method

元素对象参考手册Element Object

Example

Add an item to the list:

document.getElementById("myList").insertBefore(newItem,existingItem);

Before adding:

  • Coffee
  • Tea

After adding:

  • Water
  • Coffee
  • Tea

Try it Yourself »

Definition and Usage

The insertBefore() method can insert 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, and then add the LI element to the list.

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

Example

Move one 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:

  • CoffeeTea
  • Water
  • Milk

After adding:

  • Milk
  • Coffee
  • Tea
  • Water

Try it Yourself »

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the insertBefore() method


Syntax

node.insertBefore(newnode,existingnode)

Parameters

Parameter Type Description
newnode Node object Required. The node object to be inserted
existingnode Node object Required. The child node before which the new node will be added.

Return Value

Type Description
Node object The node you inserted/td>

Technical Details

DOM Version Core Level 1 Node Object


元素对象参考手册Element Object

Other Extensions