HTML DOM Element insertBefore() Method
- Previous Page insertAdjacentText()
- Next Page isContentEditable
- Go to Parent Level HTML DOM Elements Object
Definition and Usage
insertBefore()
The method inserts a child node before an existing child node.
See also:
Instance
Example 1
- Create an <li> element
- Create a text node
- Attach text to the <li> element
- Insert the <li> element before the first child element in <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]);
Example 2
Move the last element from one list to the beginning of another list:
const node = document.getElementById("myList2").lastElementChild; const list = document.getElementById("myList1"); list.insertBefore(node, list.children[0]);
Example 3
Move the last element from one list to the end of another list:
const node = document.getElementById("myList2").lastElementChild; const list = document.getElementById("myList1"); list.insertBefore(node, null);
Syntax
element.insertBefore(newnode, existingnode)
or
node.insertBefore(newnode, existingnode)
Parameter
Parameter | Description |
---|---|
newnode | Required. The node to be inserted (element). |
existingnode |
Optional. Insert a new node before the existing node. If not specified, the insertBefore method will insert newnode at the end. |
Return Value
Type | Description |
---|---|
Node | The node to be inserted. |
Browser Support
element.insertBefore()
It is a DOM Level 1 (1998) feature.
All browsers fully support it:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | 9-11 | Support | Support | Support | Support |
- Previous Page insertAdjacentText()
- Next Page isContentEditable
- Go to Parent Level HTML DOM Elements Object