jQuery | insertBefore() with Examples

The insertBefore() is an inbuilt method in jQuery which is used to insert some HTML content before a specified element. The HTML content will be inserted before each occurrence of the specified element.
Syntax:

$(content).insertBefore(target)

Here content is the HTML content which needs to be inserted before the specified target.
Parameters: It accepts a parameter “target” which is the target before which the content is to be inserted.
Return Type: It doesn’t return any value.

jQuery code to show the working of insertBefore() method:

Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <script 
    </script>
    <script>
        $(document).ready(function() {
            $("div").click(function() {
                // insertBefore
                $("<p>You should follow GeeksForGeeks</p>").insertBefore("p");
            });
        });
    </script>
</head>
  
<body>
  
    <p>To learn jQuery </p>
  
    <div>Click here to complete</div>
  
</body>
  
</html>

chevron_right


Output:
Before clicking the div content-

To learn jQuery
Click here to complete

After clicking the div content-

You should follow GeeksForGeeks
To learn jQuery 
Click here to complete

Code #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <script 
    </script>
    <script>
        $(document).ready(function() {
            $("div").click(function() {
                // insertBefore
                $("<p>You should follow GeeksForGeeks</p>").insertBefore("p");
            });
        });
    </script>
</head>
  
<body>
  
    <p>To learn jQuery </p>
  
    <p> To learn coding </p>
  
    <div>Click here to complete</div>
  
</body>
  
</html>

chevron_right


Output:
Before clicking the div content-

To learn jQuery 
To learn coding 
Click here to complete

After clicking the div content-

You should follow GeeksForGeeks
To learn jQuery 
You should follow GeeksForGeeks
To learn coding
Click here to complete


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 :

Be the First to upvote.


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