JavaScript insertBefore() Method

Sometimes we need to insert an element at a specific position, or we need to insert an element before any particular element. At that time we can use JavaScript insert before method.

The InsertBefore() Method

JavaScript insertBefore() method inserts a node at the specified position between HTML DOM elements.

Also Read: JavaScript appendChild() Method


Let’s consider we need to insert an element at 2nd position in the list.

<!DOCTYPE html>
  <title>Errorsea - JavaScript Insert Before</title>

<ul id="languages">

<button onclick="insert()">Insert</button>

function insert() {
  var li = document.createElement("li");
  li.innerHTML = "JavaScript";

  var list = document.getElementById("languages");
  list.insertBefore(li, list.childNodes[2]);


Note: Here we take 3rd child node’s position to insert a node at 2nd position.


  • First, we create a new <li> element using document.createElement() function.
  • Then we set it’s innerHTML value to “JavaScript”
  • Then we append newly created <li> element in the list at 2nd position.


I hope now you have a complete understanding of the insertBefore() method in JavaScript. The main use of the insertBefore() method is to insert an element at a specific position.

Enjoy Scripting 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *