jQuery before() Method

The jQuery before() method can be used to insert the specified content before the selected element. It adds the content before the element and not inside the selected element.

jQuery before() Method

Syntax

The syntax of this method is given below:-

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

Description of the Parameters

The description of these parameters is given below.

Parameter Name Description
selector Specify the element to select and add content before it. Use tag name, class name, or id of the elements to select. It is a required field.
content Specify the content to add before the selected element. It is a required field.
index It returns the index position of the element.

jQuery before() Method to Insert Content

If you want to insert or add the content before the selected element, you can use this method as given below. The example adds the specified content before the selected element and not inside it.

Example

Test it Live

Output

This is my paragraph.


The example contains the button and the paragraph element. You have to click the button to add the specified em element before the p element. Click the above button for more than one time to add the content.

Pass Function to jQuery before() Method to Add Content

You can pass the function to the jQuery before() method to insert content before the element. Use the example given below to find the use of function as a parameter of method.

Example

Test it Live

Output

This is my paragraph.


The above example contains the paragraph and the button element. Click the button to add b element before the paragraph.

You may also like to read

I hope you like this tutorial on jQuery before() method. If you have any queries regarding the tutorial, please comment below.

References