Objectives and outcomes

In this tutorial we are going to learn about jquery add content methods. There are four method to add content :-
1- append() - It is used to add content at the end of selected element.
2- prepend() - It is used to add content at the beginning of element.
3- after() - It is used to add content after the selected element.
4- before() - It is used to add content before the selected element.
Example for the same is shown below:



Syntax for method

$(selector).append('some text');
$(selector).prepend('some text');
$(selector).after('some text');
$(selector).before('some text');





Observe the change by clicking on buttons








HTML code:

<html>
<head>
<meta charset="utf-8">
<title>Jquery content addition</title>
<script src="jquery/jquery.min.js"></script>
</head>
<body>
<div id="example">
<br/>
<p id="para"><br/>Observe the change by clicking on buttons<br/></p><br/>
</div><br/>
<button id="butn1">Append</button><br/>
<button id="butn2">Prepend</button><br/>
<button id="butn3">After</button><br/>
<button id="butn4">Before</button>
</body>
</html>


CSS stylesheet

<style>
#example
{
background-color:#585858;
color:#fff;
font-size:20px;
text-align:center;
}
</style>


Javascript

<script>
$(document).ready(function()
{
$('#butn1').click(function()
{
$('#para').append("Append button is clicked");
});
		
$('#butn2').click(function()
{
$('#para').prepend("Prepend button is clicked");
});
	
$('#butn3').click(function()
{
$('#para').after("After button is clicked");
});
		
$('#butn4').click(function()
{
$('#para').before("Before button is clicked");
});
	});
</script>


Difference between .append() and .after()

append() inserts the content at last of the specified element and the content is treated as element's child whereas after() inserts the content after the specified element means the content is placed outside the element. The same is the difference with prepend() and before().