In the previous article, we have discussed about append
method. In this article, we will discuss about JQuery prepend
method.
prepend()
method is used to insert a content at the beginning of any selected element.
Syntax
$(selector).prepend(content);
In the below example, we have inserted <li>
tag in the beginning of <ul>
tag.
<!DOCTYPE html>
<html>
<body>
<ul id="list">
<li>First LI</li>
<li>Second LI</li>
</ul>
<button type="button" id="add-li">Add to list</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#add-li').click(function() {
$('#list').prepend('<li>Inserted LI</li>');
});
});
</script>
</body>
</html>
There is also another method prependTo()
, which is similar to prepend()
. In the prependTo()
, you prepend the content in prependTo()
element.
Syntax
$(content).prependTo(selector);
Here is the example of prependTo()
of above one.
<!DOCTYPE html>
<html>
<body>
<ul id="list">
<li>First LI</li>
<li>Second LI</li>
</ul>
<button type="button" id="add-li">Add to list</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#add-li').click(function() {
$('<li>Inserted LI</li>').prependTo('#list');
});
});
</script>
</body>
</html>
This way, you can use prepend()
and prependTo()
method to insert content at the beginning of any element. I hope you liked this article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Javascript Generate a Random Number
Sometimes while testing we often need to...React JS Axios File Upload Example
In this tutorial, we will provide you ex...What is new in Laravel 8?
Hello artisan, I have some good news...How to Create React Select Dropdown
If you require to visually perceive an e...How to Update the Node Version in Ubuntu
In this article i will share with you ho...