Easy Tutorial
❮ Prop Document Activeelement Event Onabort Media ❯

HTML DOM insertBefore() Method

Element Object

Example

Adding an item to the list:

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

Before adding:

Coffee
Tea

After adding:

Water
Coffee
Tea

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 text node to 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

Moving an item to another list item:

Before adding:

After adding:


All major browsers support the insertBefore() method.


Syntax

Parameters

Parameter Type Description
newnode Node Object Required. The node object to insert.
existingnode Node Object Required. The child node before which the new node is inserted.

Return Value

Type Description
Node Object The node you inserted.

Technical Details

| DOM Version | Core Level 1 Node Object | | --- | --- |


Element Object

❮ Prop Document Activeelement Event Onabort Media ❯