The prepend() method is an inbuilt method in jQuery that is used to insert specified content at the beginning of the selected element.
Syntax:
$(selector).prepend(content, function)
Parameters: This method accepts two parameters as mentioned above and described below:
- content: It is a required parameter that is used to specify the content that needs to be inserted.
- function: It is an optional parameter that is used to specify the function to perform after the call.
Return Value: This method returns the selected element with the specified changes made by prepend() method.
The below examples illustrate the prepend() method in jQuery:
Example 1: This example does not contain an optional parameter.
html
<!DOCTYPE html>
< html >
< head >
< title >The prepend Method</ title >
< script src="
</ script >
< script >
$(document).ready(function () {
$("button").click(function () {
$("p").prepend("Welcome to ");
});
});
</ script >
< style >
div {
width: 350px;
height: 100px;
font-weight: bold;
padding: 20px;
font-size: 25px;
border: 2px solid green;
}
</ style >
</ head >
< body >
< div >
< p >GeeksforGeeks!</ p >
< button >Click Here!</ button >
</ div >
</ body >
</ html >
|
Output:
Example 2: This example contains an optional parameter.
html
<!DOCTYPE html>
< html >
< head >
< title >The prepend Method</ title >
< script src =
</ script >
< script >
$(document).ready(function () {
$("button").click(function () {
$("p").prepend(function () {
return "< b >Hello ";
});
});
});
</ script >
< style >
div {
width: 350px;
height: 100px;
font-weight: bold;
padding: 20px;
font-size: 25px;
border: 2px solid green;
}
</ style >
</ head >
< body >
< div >
< p >Contributor!</ p >
< button >Click Here!</ button >
</ div >
</ body >
</ html >
|
Output:
Last Updated :
10 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...