Skip to content
Related Articles

Related Articles

Improve Article
HTML | DOM insertBefore() Method
  • Last Updated : 25 Jul, 2019

The insertBefore() method in HTML DOM is used to insert a new node before the existing node as specified by the user.


node.insertBefore( newnode, existingnode )

Parameters: This method accepts two parameters as mentioned above and described below:

  • newnode: It is the required parameter. This parameter contains the new node object which need to insert.
  • existingnode: It is the required parameter. It describes the position where new node insert before this node. If it set to null then insertBefore method will insert the new node at the end.

Return Value: It returns the node object which represent the inserted node.

Example: In this example, insert a list element before the second node of the list.

<!DOCTYPE html>
        HTML | DOM insertBefore() Method
    <!--Script to insert a new node before existing node-->
        function myGeeks() {
            var newItem = document.createElement("li");
            var textnode = document.createTextNode("Java");
            var list = document.getElementById("subjects");
            list.insertBefore(newItem, list.childNodes[2]);
        Welcome To GeeksforGeeks
        HTML DOM insertBefore() Method
    <ul id="subjects">
        Click on the button to insert an 
        element before Python
    <button onclick="myGeeks()">
        Insert Node

Before Click on the button:

After Click on the button:

Supported Browsers: The browser supported by DOM insertBefore() Method are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari

My Personal Notes arrow_drop_up
Recommended Articles
Page :