JavaScript insertBefore

The JavaScript insertBefore () is a method that is used for inserting a child node before another node of a specified parent node.

In this section, we will learn about the insertBefore () method and look at an example to understand the implementation of the insertBefore () method.

JS insertBefore() method

If we want to add a node (child node) before another node of a parent node, the insertBefore() method is used.

Syntax

In the above syntax, the parentNode is the specified parent node where the new child node will be inserted. Here, newNode signifies the node that is going to be inserted before another node and the existingNode signifies the node before which the new child node will get inserted. In case, if the existing node value is null that is it does not exist, the new node gets inserted at the end of the parentNode's child nodes.

How insertBefore() function works

The method follows the below steps:

  • Firstly, the method searches for the specified parent node in the code.
  • Then, it looks for the existing node value, whether found in the parent node.
  • The method returns null if no existing node is found before which the user wish to insert a new node.
  • Next, if the existing node is available in the specified parent node, the method inserts the new node before the existing node and returns the inserted child node.

Example of insertBefore() Method

Below is an example code that will help us to understand the working of insertBefore() method:

The output of the above code is shown below:

JavaScript insertBefore

In the above code:

The above code is html and JavaScript based code:

First, we have created an unordered list with an id ="weeks" given to it. The list contains some items enclosed within the

  • element.