jQuery

jQuery append Method Examples

If you ever wanted to insert content, text or html or both, after the content of the matched elements but did not know how to do it, then you can use the  jQuery append method. Using it, you can easily add content, dynamic or static. In this article, I am going to share info on the append() method along with easy to follow examples.

How to use jQuery append method

So let’s see how to use the .append() method with a simple, easy to follow example. This example assumes that we have 2 main divs with class “red” & “green” applied to them & these divs are held in another “container” div for easy manipulation. So what we are going to do is have 2 individual buttons that will let you append the red div to green div and vice-versa.  We also have another button that will reset the divs back to their original state, once the append method has been used on them dynamically.

Here is the complete source code:

<html>
<head>
<title>Easy examples for using the .append() method in jQuery</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<style type="text/css">
.red {
	background-color: #FFA6A6;
	border: 1px solid red;
	margin: 10px;
}
.green {
	background-color: #CEFFCE;
	border: 1px solid green;
	margin: 10px;	
}
</style>
</head>

<body>

<div class="divs_container">

<div id="mydiv1" class="red">This is my 1 div</div>

<div id="mydiv2" class="green">This is my 2 div</div>

</div>

<input type="button" name="sbt_append_g2r" id="sbt_append_g2r" value="Append Green Div to Red">
<input type="submit" name="sbt_remove" id="sbt_remove" value="Unappend/Remove">
<input type="button" name="sbt_append_r2g" id="sbt_append_r2g" value="Append Red Div to Green">

<script type="text/javascript" language="javascript" >

$(document).ready(function(){

	var divs_container_html = $(".divs_container").html();

	//Append Green Div to Red
	$('#sbt_append_g2r').on("click", function(){

		$('.red').append($('.green'));

	});

	//Append Red Div to Green
	$('#sbt_append_r2g').on("click", function(){

		$('.green').append($('.red'));

	});	

	//Reset the divs back to their original state
	$('#sbt_remove').on("click", function(){		

		$(".divs_container").html(divs_container_html); 

	});		

});

</script>
</body>
</html>
That’s it for now!

Do you know of any other ways to use jQuery append method? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*