Home >>jQuery Tutorial >jQuery prepend() Method

jQuery prepend() Method

jQuery prepend() Method

jQuery prepend() method in jQuery is used to inserts specified content at the start of the selected elements.

Syntax:
$(selector).prepend(content,function(index,html))

Parameter Values

Parameter Description
content It is required parameter and is used to Specifies the content to insert

Possible values:

  • jQuery objects
  • HTML elements
  • DOM elements
function(index,html) It is optional parameter and is used to Specifies a function that returns the content to insert
  • index – it is used to returns the index position of the element
  • html – it is used to returns the current HTML of the selected element
Here is an Example of jQuery prepend() Method:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$(".txt1").prepend("<b>Prepended text</b>. ");
});
$("#btn2").click(function(){
$(".pretxt").prepend("<li>Prepended item</li>");
});
});
</script>
</head>
<body>
<p class="txt1">This is first paragraph.</p>
<p class="txt1">This is second paragraph.</p>
<ol class="pretxt">
<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</button>
</body>
</html>

Output:

This is first paragraph.

This is second paragraph.

  1. List item 1
  2. List item 2
  3. List item 3