HTML DOM Element insertBefore()

Examples

  1. Create an <li> element
  2. Create a text node
  3. Append the text to the <li> element
  4. 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.



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
NodeThe 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

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.