- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
parameters | Description |
---|---|
newNode | It is the newly created child node which is to be appended at beginning |
existingNode | It is the already existing node |
Example
Let us see an example for InsertBefore() method −
<!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 −
Advertisements