Sometimes we need to insert an element at a specific position, or we need to insert an element before any particular element. At that time we can use JavaScript insert before method.
Index
The InsertBefore() Method
JavaScript insertBefore() method inserts a node at the specified position between HTML DOM elements.
Also Read: JavaScript appendChild() Method
Example
Let’s consider we need to insert an element at 2nd position in the list.
<!DOCTYPE html> <html> <head> <title>Errorsea - JavaScript Insert Before</title> </head> <body> <ul id="languages"> <li>Java</li> <li>PHP</li> <li>Python</li> </ul> <button onclick="insert()">Insert</button> <script> function insert() { var li = document.createElement("li"); li.innerHTML = "JavaScript"; var list = document.getElementById("languages"); list.insertBefore(li, list.childNodes[2]); } </script> </body> </html>
Note: Here we take 3rd child node’s position to insert a node at 2nd position.
Explanation
- First, we create a new <li> element using document.createElement() function.
- Then we set it’s innerHTML value to “JavaScript”
- Then we append newly created <li> element in the list at 2nd position.
Conclusion
I hope now you have a complete understanding of the insertBefore() method in JavaScript. The main use of the insertBefore() method is to insert an element at a specific position.
Enjoy Scripting 🙂