jQuery | before() Method

The before() Method in jQuery is used to add content before the selected element.

Syntax:

$(selector).before( content, function(index) )

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



  • content: This parameter holds the content to be inserted before the element. The possible value of content can be HTML Elements, DOM Elements, jQuery Elements.
  • function(index): It is optional parameter and used to specify a function that returns the content to insert before the element and index returns the index positioning of element.

Example 1: This example insert the content before the element.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        jQuery before() Method
    </title>
      
    <script src=
    </script>
      
    <!-- Script to insert element before button element -->
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("button").before("<p>GeeksforGeeks:"
                + " A computer science portal</p>");
            });
        });
    </script>
</head>
  
<body>
    <button>Click Here to Insert element before button</button>
</body>
  
</html>     

chevron_right


Before click on the button:

After click on the button:

Example 2: This example insert content before the specified element.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        jQuery before() Method
    </title>
      
    <script src=
    </script>
      
    <!-- Script to add content before the element -->
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("span").before("<span>GeeksforGeeks: </span>");
            });
        });
    </script>
</head>
  
<body>
    <span>A computer science portal for geek</span><br>
      
    <span>A computer science portal for geek</span><br>
      
    <span>A computer science portal for geek</span><br>
      
    <button>Click to insert</button>
</body>
  
</html>

chevron_right


Before Click on the button:

After Click on the button:



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.