jQuery after() and insertAfter() example

In this post,  we are going to see jQuery after and insertAfter methods.
Both do the same task, insert text or html after every selected elements but syntax is quite different. 

Syntax for after():

$("selectors").after("element to be inserted") ;
Example :
$("div").after("<p class='red'>inserting using after</p>");

Syntax for insertAfter() :

$("element to be inserted") .insertAfter("div");
Example:
$("<p class='blue'>inserting using insertAfter</p>").insertAfter("div");
Let's understand with the help of example:
<!doctype>
<html>
<head>
  <title>Jquery after and insertAfter example example </title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery after and insertAfter example 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;
   }
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#afterButton").click(function(){
         $("div").after("<p class='red'>inserting using after</p>");
      });
$("#insertAfterButton").click(function(){
         $("<p class='blue'>inserting using insertAfter</p>").insertAfter("div");
      });
$("#reset").click(function(){
         location.reload();
   });
 });

</script>
<body>
  <button id="afterButton">Using after</button>

  <button id="insertAfterButton">Using insertAfter</button>
<button id="reset">Reset</button>
<div>
 Hello world from java2blog!!!!
   </div>
<div>
 Welcome to JQuery.
  </div>
</body>
</html>
Live demo: Jquery after and insertAfter example 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