jQuery prepend function add the content to the start of the selected HTML element.
You just required to select and access the HTML element first using the jQuery selectors. After getting the required element you have to use the jQuery prepend function using the syntax given below.
If you want to add the content at the end of the HTML element, you have to use the jQuery Append function or jQuery appendTo().
Syntax of jQurey prepend function
1 |
$(selector).prepend(content,function(index,html)) |
Sr. No | Parameter Name | Description |
---|---|---|
1 | selector | The selector parameter is the first required parameter used to select the required HTML element and prepend the content. It is the required parameter. |
2 | content | The content parameter is used to specify the content and insert at the start of the selected element. It is the required parameter. |
3 | function(index,html) | It is the function that returns the content which is inserted. It is the optional parameter. |
Example of jQuery Prepend Function
See the below given example of jQuery prepend()
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $("#btn-prepend").click(function(){ $("#para-prepend").prepend("This is the prepended text."); }); }); </script> <button id="btn-prepend">Click me to prepend</button> <p id="para-prepend">Welcome to the Tutorialdeep jQuery Tutorial.</p> |
Output
Welcome to the Tutorialdeep jQuery Tutorial.
The above example inserts the text at the start of the p element when you click the button.
The jQuery prepend function inserts the content after you click the button. If you click the button two times, it inserts the content at the start for two times. The number of times you click the button, the number of times it inserts the content to the start of the HTML element.
Example1: jQuery Prepend with HTML tags inside the content
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $("#btn-prependtag").click(function(){ $("#para-prependtag").prepend("<span>This is the <strong>inserted</strong> text with <b>HTML tags</b>.</span>"); }); }); </script> <button id="btn-prependtag">Click me to prepend</button> <p id="para-prependtag">This is the jQuery Tutorial.</p> |
Output
This is the jQuery Tutorial.
The above example contains the content with three tags span, strong and b. When you click the click me button, the jQuery prepend function add the content at the start of the HTML element with the output of these tags.
Now, the same thing applies here as you have noted above, The more the number of times you click the button, the prepend function inserts the content at the start for that number of times.