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 »
The insertBefore()
method inserts a child node before an existing child.
element.insertBefore(
new, existing)
node.insertBefore(
new, existing)
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. |
Type | Description |
Node | The inserted node. |
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 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!