The jQuery prepend() method inserts the specified content at the the beginning of selected elements. This works just opposite to the append() method that we discussed earlier here.
Syntax of prepend() method
$(selector).prepend(content)
Here, content represents the specified data that is inserted at the start of the selected elements. This content can include HTML tags, jQuery objects, DOM elements or simple text/strings etc.
Example 1: jQuery prepend() Method
In this example, we have a page with two p elements (paragraphs). We are appending a specified text at the beginning of these p elements using prepend() method.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").prepend("<b><i>Newly appended Text<i></b>.");
});
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<button>Prepend text</button>
</body>
</html>
Output:
Before button click:
After button click: You can see that we specified the html tags <b> for bold and <i> for italic and the prepend method used them while inserting the text. The inserted text is bold and italic.
Example 2: jQuery prepend() Method
Here we have a list of list items and two p elements on a page. We have two buttons, one with id “b1” and other with id “b2”.
On the click of button with id “b1”, we are using prepend() method to insert the text before p elements.
On the click of button with id “b2”, we are using prepend() method to insert the new list item at the beginning of the list. This means existing list items will be shifted down to one position and the new item would take first place in the list as shown in the output screenshot.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#b1").click(function(){
$("p").prepend("<b>Newly Inserted Text</b>. ");
});
$("#b2").click(function(){
$("ol").prepend("<li>NewListItem</li>");
});
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<ol>
<li>ListItem1</li>
<li>ListItem2</li>
<li>ListItem3</li>
</ol>
<button id="b1">Prepend text before p elements</button>
<button id="b2">Prepend list item before list elements</button>
</body>
</html>
Output:
Before any button click:
After “Prepend text” button click:
After “Prepend list” button click: