Insert content at the beginning of all <p> elements:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>//from w w w . j av a2 s. c o m <script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").prepend("<b>Prepended text</b>. "); }); $("#btn2").click(function(){ $("ol").prepend("<li>Prepended item</li>"); }); }); </script> </head> <body> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ol> <button id="btn1">Prepend text</button> <button id="btn2">Prepend list item</button> </body> </html>
The prepend()
method inserts content at the beginning of the selected elements.
To insert content at the end of the selected elements, use the append()
method.
$(selector).prepend(content,function(index,html))
Parameter | Optional | Description |
---|---|---|
content | Required. | Specifies the content to insert Possible values: HTML elements jQuery objects DOM elements |
function(index,html) | Optional. | sets a function that returns the content to insert index - the index position of the element in the set html - the current HTML of the selected element |