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))
Parameters of jQuery prepend() method
Parameter | Description |
---|---|
Content | It is a mandatory parameter. It specifies the content which you want to insert. Its possible values are:HTML elementsjQuery objectsDOM elements |
Function (index, html) | It is an optional parameter. It specifies a function that returns the content which is inserted.Index:It is used to provide the index position of the element in the set.Html: : It provides the current HTML of the selected element. |
Example of jQuery prepend() method
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.Prepend text
jQuery prepend() example 2
- <!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.
- Item no.1
- Item no.2
- Item no.3
Prepend text Prepend list item
jQuery prepend() example 3
<!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>javatpoint.com</p>
<p>Guys! Welcome to the best tutorial site.</p>
<script>
$( "p" ).prepend( "<b>Hello </b>" );
</script>
</body>
</html>
Output:
Hello wisdom.com
Hello Guys! Welcome to the best tutorial site.
Leave a Reply