Both jQuery prepend() and prependTo() methods are doing the same task, add a text or html content before the content of the matched elements. The major difference is in the syntax.

For example,

<div class="box">I'm a big box</div>
<div class="box">I'm a big box 2</div>

1. $(‘selector’).prepend(‘new text’);

$('.box').prepend("<div class='newbox'>I'm new box by prepend</div>");

2. $(‘new text’).prependTo(‘selector’);

 $("<div class='newbox'>I'm new box by prependTo</div>").prependTo('.box');

Result

Both methods above are doing the same task, but with different syntax, the new contents after prepend() or prependTo() will become
This is really versatile tool to have. For any website on which you want a slider this is the way to do it. If you look at any of the big websites, for example one like www.o2.co.uk/ or a film website you are likely to see one in use. It is a great way to have a rotation of images that looks smart and catches the eye of the viewer. It adds a different dimension to your website that will make it really stand out above the rest.

<div class="box">
   <div class='newbox'>I'm new box by prepend</div>
   I'm a big box
</div>
 
<div class="box">
   <div class='newbox'>I'm new box by prepend</div>
   I'm a big box 2
</div>

Try it yourself

<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
 
<style type="text/css">
	.box{
		padding:8px;
		border:1px solid blue;
		margin-bottom:8px;
		width:300px;
		height:100px;
	}
	.newbox{
		padding:8px;
		border:1px solid red;
		margin-bottom:8px;
		width:200px;
		height:50px;
	}
</style>
 
</head>
<body>
  <h1>jQuery prepend() and prependTo example</h1>
 
  <div class="box">I'm a big box</div>
 
  <div class="box">I'm a big box 2</div>
 
  <p>
  <button id="prepend">prepend()</button>
  <button id="prependTo">prependTo()</button>
  <button id="reset">reset</button>
  </p>
 
<script type="text/javascript">
 
    $("#prepend").click(function () {
 
	  $('.box').prepend("<div class='newbox'>I'm new box by prepend</div>");
 
    });
 
    $("#prependTo").click(function () {
 
	  $("<div class='newbox'>I'm new box by prependTo</div>").prependTo('.box');
 
    });
 
    $("#reset").click(function () {
	  location.reload();
    });
 
</script>
</body>
</html>
Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website mkyong.com is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time my server is down. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts