The jQuery prepend() method is used to insert the specified content at the beginning (as a first child) of the selected elements. It is just the opposite of the jQuery append() method.
If you want to insert the content at the end of the selected elements, you should use the append method.
Syntax:
$(selector).prepend(content,function(index,html))
Parameter | Description |
---|---|
Content | It is a mandatory parameter. It specifies the content which you want to insert. Its possible values are:
|
Function (index, html) | It is an optional parameter. It specifies a function that returns the content which is inserted.
|
Let's take an example to demonstrate the jQuery prepend() method.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").prepend("<b>Prepended text</b>. "); }); }); </script> </head> <body> <p>This is the first paragraph.</p> <p>This is the second paragraph.</p> <button id="btn1">Prepend text</button> </body> </html>
Output:
This is the first paragraph.
This is the second paragraph.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <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 the first paragraph.</p> <p>This is the second paragraph.</p> <ol> <li>Item no.1</li> <li>Item no.2</li> <li>Item no.3</li> </ol> <button id="btn1">Prepend text</button> <button id="btn2">Prepend list item</button> </body> </html>
Output:
This is the first paragraph.
This is the second paragraph.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>prepend demo</title> <style> p { background: lightpink; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <p>rookienerd.com</p> <p>Guys! Welcome to the best tutorial site.</p> <script> $( "p" ).prepend( "<b>Hello </b>" ); </script> </body> </html>
Output:
Hello rookienerd.com
Hello Guys! Welcome to the best tutorial site.