jQuery before() and insertBefore() example

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

Syntax for after():

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

Syntax for insertBefore() :

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

</script>
<body>
  <button id="beforeButton">Using before</button>

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