Open In App

jQuery before() Method

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

Syntax:



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

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

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






<!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>

Output:

 

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




<!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>

Output:

 


Article Tags :