HTML DOM Element insertBefore()
Examples
- Create an <li> element
- Create a text node
- Append the text to the <li> element
- Insert the <li> element before the first child in a <ul>:
const newNode = document.createElement("li");
const textNode = document.createTextNode("Water");
newNode.appendChild(textNode);
const list = document.getElementById("myList");
list.insertBefore(newNode, list.children[0]);
Try it Yourself »
Move the last element from one list to the beginning of another:
const node = document.getElementById("myList2").lastElementChild;
const list = document.getElementById("myList1");
list.insertBefore(node, list.children[0]);
Try it Yourself »
Move the last element from one list to the end of another:
const node = document.getElementById("myList2").lastElementChild;
const list = document.getElementById("myList1");
list.insertBefore(node, null);
Try it Yourself »
Description
The insertBefore()
method inserts a child node before an existing child.
See Also:
Syntax
element.insertBefore(new, existing)
or
node.insertBefore(new, existing)
Parameters
Parameter | Description |
new | Required. The node (element) to insert. |
existing | Required. The node (element) to insert before. If null , it will be inserted at the end. |
Return Value
Type | Description |
Node | The inserted node. |
Browser Support
element.insertBefore()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |