To prepend HTML content using jQuery, you can use the prepend()
method. This method inserts the specified content as the first child of each element in the selected set of elements.
To prepend HTML content using jQuery, you can use the following syntax:
$(selector).prepend(content);
$(selector)
: This is the jQuery selector that targets the element(s) to which you want to prepend the content. It can be an element selector, class selector, ID selector, or any other valid jQuery selector..prepend(content)
: This is theprepend()
method that inserts the specifiedcontent
as the first child of each selected element.content
: This parameter represents the HTML content that you want to prepend. It can be a string of HTML tags, a DOM element, or a jQuery object.
$(document).ready(function() {
$("#myDiv").prepend("<p>This is some prepended content.</p>");
});
jQuery prepend HTML example
A simple example code demonstrates how to use the prepend()
method to prepend HTML content using jQuery:
<!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() {
$("#myDiv").prepend("<p>This is some prepended content.</p>");
});
</script>
</head>
<body>
<div id="myDiv">
<p>This is the original content.</p>
</div>
</body>
</html>
Output:
The new paragraph <p>This is some prepended content.</p>
is added as the first child of the “myDiv” element, while the original content paragraph remains below it.
Do comment if you have any doubts or suggestions on this jquery code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version