jQuery prepend and prependTo example

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

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

  <button id="prependButton">Using prepend</button>
  <button id="prependToButton">Using prependTo</button>
<button id="reset">Reset</button>
<div class='blackBorder'>
 Hello world from java2blog!!!!
<div class='blackBorder' >
 Welcome to JQuery.
Live demo: JS Bin 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