How to use Append() and Prepend() method in JQuery
Understand Append()
and Prepend() method in JQuery
With JQuery we can dynamically add text in almost all HTML
elements. There are several methods to do it. Here we will see how to add text
and HTML element using append and prepend method of JQuery.
Append text to
<p> element
We can use append method to append and HTML element or text
to existing HTML element. In this example,we will see how to append text to
<p> element.
<html>
<head>
<title>Untitled Document</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});
});
</script>
</head>
<body>
<p>This is a static text</p>
<button id="btn1">Append text</button>
</body>
</html>

Append element to existing
element
Not only text, but we can also add/append HTML element to existing
HTML element. In this example, we will see how to add list item dynamically to an
existing list.
<html>
<head>
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("ol").append("<li>Appended item by JQuery</li>");
});
});
</script>
</head>
<body>
<ol>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">Append text</button>
</body>
</html>

Prepend text to
<p> element
Prepend is just opposite to append. It will add text just before
to <p> element’s text. In below there is sample example.
<html>
<head>
<title>Untitled Document</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").prepend("<b>Prepend text</b>.");
});
});
</script>
</head>
<body>
<p>This
is a static text</p>
<button
id="btn1">Prepend text</button>
</body>
</html>

Prepend list item to existing
list.
We can use prepend to add any HTML element before any existing
element. Have a look on below example.
<html>
<head>
<title>Untitled Document</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("ol").prepend("<li>Prepend item by
JQuery</li>");
});
});
</script>
</head>
<body>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">Prepend Item</button>
</body>
</html>
