The following code shows an Example of insertBefore() Method in JavaScript.

Programmingempire

Illustrating an Example of insertBefore() Method in JavaScript

This method inserts an HTML element at the specified position. As can be seen in the following code, when a user enters a text, it creates an <li> element. After that, it inserts it before the element at index 0.

<html>
<head>
  <title>insertBefore Method Demo</title>
  <script>
     function f1()
     {
        var v1=document.getElementById("t1"); 
        var v2=document.getElementById("t2"); 
        var str=v2.value;
        if(str!=""){
        v2.value="";
        var x=document.createElement("LI");
        var y=document.createTextNode(str);
        x.appendChild(y);
        v1.insertBefore(x, v1.childNodes[0]);}
     }
  </script>
  <style>
    .c1{
       border: 4px solid #33ff99;
       border-radius: 10px;
       background-color: #5566aa;
       color: #aaffff;
       font-size: 20px;
       text-align: center;
       margin:5px;
       padding: 10px;
      }
    .a1{
		margin: 50px;
	}
    .c2{
       background-color: #ddeeff;
       color: #ff5566;
       font-size: 25px;
       text-align: left;
       margin:40px;
       padding: 5px;
       width: 800px;
      }
  </style>
</head>
<body>
  <div id="d1" class="c2"><br/><br/>
     Example of insertBefore() Method<br/>
     <br/><br/>
     List of Colors....<br/>
     <ul id="t1">
       <li>Red</li>
       <li>Blue</li>
       <li>Green</li>
     </ul>
     <br/>Enter Another Color: <input id="t2" type="text" onchange="f1()"/>
 </div>
</body>
</html>

Output

The Output of an Example of insertBefore() Method in JavaScript
The Output of an Example of insertBefore() Method in JavaScript

Further Reading

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

Creating User-Defined Functions in javaScript

Popup Boxes in JavaScript

programmingempire