Insert a new <li> element before the first child element of an <ul> element:
Before inserting:
After inserting:
More "Try it Yourself" examples below.
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").
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
insertBefore() | 1.0 | Yes | 1.0 | Yes | Yes |
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 |
Return Value: | A Node Object, representing the inserted node |
---|---|
DOM Version | Core Level 1 Node Object |
Move a <li> element from one list to another:
Before inserting:
After insertBefore: