HTML DOM insertBefore( ) Method


The HTML DOM insertBefore() method inserts a new node before an already existing child node.

Syntax

Following is the syntax −

Calling insertBefore() with parameters of positionString and text

node.insertBefore(newNode, existingNode)

Here, parameters can be the following −

Parameters

parametersDescription
newNodeIt is the newly created child node which is to be appended at beginning
existingNodeIt is the already existing node

Example

Let us see an example for InsertBefore() method −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>insertBefore()</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
   ol {
      width:30%;
      margin: 0 auto;
   }
</style>
</head>
<body>
<form>
<fieldset>
<legend>insertBefore( )</legend>
<h1>How to make tea</h1>
<h3>Steps:</h3>
<ol id="stepList">
<li>Add Tea Bag</li>
<li>Add Sugar</li>
<li>Add Milk</li>
</ol>
<input type="button" onclick="addStep()" value="Add">
</fieldset>
</form>
<script>
   function addStep() {
      var newIngredient = document.createElement("LI");
      var textnode = document.createTextNode("Boil Water");
      newIngredient.appendChild(textnode);
      var stepList = document.getElementById("stepList");
      stepList.insertBefore(newIngredient, stepList.childNodes[0]);
   }
</script>
</body>
</html>

Output

This will produce the following output −

Before clicking ‘Add’ button −

After clicking ‘Add’ button −

Updated on: 30-Jul-2019

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements