The jQuery prependTo() method can be used to insert the HTML content at the beginning of the selected element. You have to specify the content to add before the selected element content.
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 to add HTML content to it. 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 the start 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. |
jQuery prependTo() Method to Add Content At The Beginning
If you want to add the content at the beginning, you have to use the jQuery prependTo() Method as given below. The method takes a parameter as the element to select and add content.
Example
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("<b>Learn jQuery from TutorialDeep.<b> ").prependTo("p"); }); }); </script> <p>This is my paragraph.</p><br> <button type="button" class="mybtn">Click to Add Content</button> |
Output
This is my paragraph.
Click the button given above to insert the HTML content at the beginning of the selected element. You can also use the prepend() method to add the content at the beginning.
Both prepend() and prependTo() perform the same tasks. However, prepend() takes content as the parameter while the prependTo() takes an element as the parameter to content.
You may also like to read
I hope you like this tutorial on jQuery prependTo() method. If you have any queries regarding the tutorial, please comment below.
References