JavaScript insertBefore method

In this section you will see that how we can insert new node or element before the referenced node as a child node of the current node and in it the current node will be act as the parent node.

JavaScript insertBefore method

JavaScript insertBefore method

     

In this section you will see that how we can insert new node or element before the referenced node as a child node of the current node and in it the current node will be act as the parent node.

 

 

 

 

 

Syntax:

 parentElement.insertBefore( newElement, referenceElement);

where newElement is the new element node which is to be inserted and referenceElement is the element before which we have to insert newElement

Description of code:

In the following html example code we have created a button "Insert Before" when user clicks on this button it calls the function funcInsertBefore() as defined in the <script></script> tag. In this function we have first created the element and after that we have used the method document.getElementById() to get the parent element object reference and then used the method insertBefore() to insert new element as a child of current parent element. Here is the full example code of the html code as described below :

<html>
<body>
<script language="JavaScript">
  function funcInsertBefore() {
   var elmnt = document.createElement('<div id="id1" style="width:300; 
  height:50;background-color:#c9c9ad;"></div>');
   document.getElementById('div1').insertBefore(elmnt);
   document.all.namedItem("id1").innerText = "Inner text of div is 
     changed using namedItem() method";
   } 
</script>
<center>
<div id="div1" style="width: 432; height: 154">
 <table border="0" width="100%" bgcolor="#800080">
 <tr>
 <td width="100%">
 <h1 align="center">
   <font color="#FFFFFF">
  &nbsp;insertBefore method
   </font>
 </h1>
 </td>
 </tr>
 </table>
</div>
<p align="center">Rose India Technologies Pvt. Ltd.
  <p align="center">
   <input type="button" onclick="funcInsertBefore(); this.disabled='true';"
   value="Insert Before" />
</p>
</center>
</body>
</html>

Output :

Download Source Code