HTML | DOM insertBefore() Method

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

Syntax:

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:
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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.