jQuery prepend() method can be used to add the content at the beginning of the selected element. You have to specify the content to insert to the start of the element.
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 add HTML content. You can use tag name, class name, or id of the elements to select. It is a required field. |
content | Specify the HTML content to add to beginning of the selected element. It is a required field. It can be HTML tags, jQuery objects, and DOM elements to add to the selected element. |
index | It returns the index position of the element. |
html | It returns the HTML content of the selected element. |
jQuery prepend() Method to Insert Content At The Beginning
If you want to add the content at the beginning of the selected element, you have to use the method as given below. Specify the content as the parameter of the method to insert to the element.
Example
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $('.myaddbtn').click(function(){ $("p").prepend("<em>Welcome to TutorialDeep!</em> "); }); }); </script> <p>Learn jQuery with tutorials and live examples.</p><br> <button type="button" class="myaddbtn">Click to Add Content</button> |
Output
Learn jQuery with tutorials and live examples.
When you click the button given above, the jQuery prepend() method add content at the start of the selected element.
Use Function to Add Content
You can also use the function with the jQuery prepend() method to insert content at the beginning. See the example given below to use the function. Specify the content inside the function to add to the element.
Example
1 2 3 4 5 6 7 8 9 10 11 |
<script> $(document).ready(function(){ $('.myaddfnbtn').click(function(){ $("p").prepend(function(){ return "<em>Learn jQuery and</em> "; }); }); }); </script> <p>Use our live examples.</p><br> <button type="button" class="myaddfnbtn">Click to Add Content</button> |
Output
Use our live examples.
Click the button to add the content at the beginning. The content is added to the selected element as specified inside the function.
You may also like to read
I hope you like this tutorial on jQuery html() method. If you have any queries regarding the tutorial, please comment below.
References