jQuery append and append to example

In this post,  we are going to see jQuery append and appendTo methods.
Both do the same task, insert text or html after content of every selected elements, so it will put text or html to last index of selected element. Both methods add text or html as a child to selected elements .Syntax is quite different for append and appendTo methods. 
Syntax for append() :
$("selectors").append("element to be inserted")
Example :
$("div").append("<p class='red'>inserting using append</p>");
Syntax for appendTo() :
$("element to be inserted") .appendTo("div");
Example:
 $("<p class='blue'>inserting using appendTo </p>").appendTo("div");

Let's understand with the help of example:
<!doctype>
<html>
<head>
  <title>Jquery append and appendTo example </title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery append and appendTo example</h2>
<style>
   .red{
        border:3px dotted red;
        color:red;
        font-family: arial narrow;
   }
 .blue{
        border:3px dotted red;
        color:blue;
        font-family: arial narrow;
   }
.blackBorder{
        border:4px dotted black;
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#appendButton").click(function(){
         $("div").append("<p class='red'>inserting using append</p>");
      });
$("#appendToButton").click(function(){
         $("<p class='blue'>inserting using appendTo</p>").appendTo("div");
      });
$("#reset").click(function(){
         location.reload();
   });
 });

</script>
<body>
  <button id="appendButton">Using append</button>
  <button id="appendToButton">Using appendTo</button>
<button id="reset">Reset</button>
<div class='blackBorder'>
 Hello world from java2blog!!!!
   </div>
<br/>
<div class='blackBorder' >
 Welcome to JQuery.
  </div>
</body>
</html>
Live demo: Jquery append and appendTo example on jsbin.com

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012