jQuery before() Method (original) (raw)
Last Updated : 27 Oct, 2022
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:
- 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 an optional parameter and is used to specify a function that returns the content to insert before the element and the index returns the index positioning of the element.
Example 1: This example inserts the content before the element.
HTML `
jQuery before() Method<!-- Script to insert element before button element -->
<script>
$(document).ready(function () {
$("button").click(function () {
$("button").before("<p>GeeksforGeeks:"
+ " A computer science portal</p>");
});
});
</script>
Click Here to Insert element before button
`
Output:
Example 2: This example inserts content before the specified element.
HTML `
jQuery before() Method<!-- Script to add content before the element -->
<script>
$(document).ready(function () {
$("button").click(function () {
$("span").before("<span>GeeksforGeeks: </span>");
});
});
</script>
A computer science portal for geekA computer science portal for geek
A computer science portal for geek
Click to insert
`
Output: