The jQuery insertBefore() method can be used to insert the content before the selected content. You have to specify the element as the parameter of the method to select.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of these parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the element to select and insert the content before it. You have to use tag name, class name, or id of the elements to select. It is a required field. |
content | You have to specify the content to insert before the selected element. It is a required field. |
jQuery insertBefore() Method to Insert Content
If you want to insert content before the selected element, you have to use the example as given below. Specify the content first and after that pass element as a parameter of the method to select.
Example
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("<em>This is an italic text. </em>").insertBefore("p"); }); }); </script> <p>This is my paragraph.</p><br> <button type="button" class="mybtn">Click to Insert Content</button> |
Output
This is my paragraph.
The above example contains the paragraph text content and the button element. You can click the button given above to insert content em element before the paragraph.
You may also like to read
I hope you like this tutorial on jQuery insertBefore() method. If you have any queries regarding the tutorial, please comment below.
References