jQuery prepend() method is used to insert content at the beginning of the selected elements. It is often used to add new elements or text before the existing content of an element.
The syntax for using the prepend()
method is as follows:
$(selector).prepend(content)
Here, $(selector)
is used to select the element(s) to which the content will be prepended, and content
represents the content that will be inserted.
The content
parameter can be specified in several ways:
1. As a string: You can provide a string of HTML or plain text that will be inserted as the first child of the selected element(s).
$("div").prepend("<p>Hello!</p>");
This will insert the <p>Hello!</p>
element as the first child of all <div>
elements on the page.
2. As a jQuery object: You can pass a jQuery object containing one or more elements that you want to insert.
var newElement = $("<p>Hello!</p>");
$("div").prepend(newElement);
This will prepend the newElement
object as the first child of all <div>
elements on the page.
3. As a function: You can use a callback function to dynamically generate the content to be inserted. The function will be executed for each selected element, and its return value will be prepended.
$("div").prepend(function() {
return "<p>Hello, " + $(this).attr("data-name") + "!</p>";
});
This will prepend a <p>
element with a personalized greeting based on the data-name
attribute of each <div>
element.
The prepend()
method can be chained with other jQuery methods to perform additional operations on the newly inserted content or the selected elements.
It’s worth noting that the prepend()
method modifies the DOM directly and returns the modified element(s), allowing for method chaining.
jQuery prepend() method example
Simple example code.
<!DOCTYPE html>
<html>
<head>
<title>jQuery prepend() Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Prepend a <p> element with a message to each <div> element
$("div").prepend("<p>Hello, I'm prepended!</p>");
// Prepend a custom message using a callback function
$("ul li").prepend(function() {
var index = $(this).index() + 1;
return "<span>" + index + ". </span>";
});
});
</script>
<style>
span {
font-weight: bold;
}
</style>
</head>
<body>
<div>First div</div>
<div>Second div</div>
<div>Third div</div>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Banana</li>
</ul>
</body>
</html>
Output:
When you run this example in a web browser, it will modify the DOM and prepend the specified content to the selected elements, resulting in the following structure:
Comment if you have any doubts or suggestions on this jQuery method topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version