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");
 $("<p class='blue'>inserting using insertBefore</p>").insertBefore("div");
Let's understand with the help of example:
  <title>Jquery before and insertBefore example </title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
<h2>Jquery before and insertBefore example </h2>
        border:3px dotted red;
        font-family: arial narrow;
        border:3px dotted red;
        font-family: arial narrow;
<script type="text/javascript">
         $("div").before("<p class='red'>inserting using before</p>");
         $("<p class='blue'>inserting using insertBefore</p>").insertBefore("div");

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

  <button id="insertBeforeButton">Using insertBefore</button>
<button id="reset">Reset</button>
 Hello world from java2blog!!!!
 Welcome to JQuery.
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