Main Tutorials

jQuery prepend() and prependTo() example

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>

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
daniel
10 years ago

Hi thanks for the tutorial I have a question, here’s a simple code

Txt1
Txt2

I’d like to insert between Umain1 and Umain3 (I don’t have a problem reaching the external div with id=”main” but I can’t find a way to reach the nested divs in advance thanks