jQuery Before Method

jQuery before function add content before the selected HTML element. The content can be any HTML element with HTML tag you want to insert before the matched HTML element.

The jQuery prepend() and jQuery before() are different actions performing functions. jQuery prepend function adds the content before the the text of the HTML element while jQuery before() function add content like HTML element before the matched content of the selected HTML element.

Below is the syntax you have to use for before(). Check the syntax first to use this function.

Syntax

Sr. NoParameter NameDescription
1selectorThe selector parameter is used to specify the HTML element you want to match and perform the before() method. It is the required field.
2contentSpecify the required content with HTML tags you want to insert before the matched content using the content parameter. It is the required field.
3function(index)Specify the function that returns the content which is inserted. It is the optional parameter.

The before() syntax needs two parameters to insert. Specify the first parameter called selector to select the HTML element using the jQuery selectors. After accessing the required element you have to specify the content you to put before the matched content.

See the example given below to learn how to use jQuery before().

Example of jQuery before Function

You can use below given example of jQuery before() in your project. Copy and make some changes according to your needs.

Test it Live

Output

When you click the below button, it adds content before the below given content.

Learning is my passion.

The above-given example adds the content before the matched you have specified. Here, In this example, font awesome icon added before the span element on click of the button.

The function adds the specified contents on click of the button. If you click the button for more than one time, it adds the content for the number of times you click the button.

Add Multiple content Using the jQuery before()

To add more than one content using the jQuery before(), you have to put multiple argument inside the before function with comma separation.

Test it Live

Output

When you click the below button, it adds multiple content together before the below given content.

Learning is my passion.

Click the button given above to see the result of inserting multiple contents and check the output. On click of the button, the function inserts the multiple contents and when you click it for more than one time, it inserts multiple contents multiple times.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.